首页 > 其他 > 详细

LeetCode: Count and Say 题解

时间:2014-06-13 00:53:50      阅读:530      评论:0      收藏:0      [点我收藏+]

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

本题的难点在于理解题目的意思。

最好的理解就是给出 111221之后的一个sample: 312211

如何理解呢?  将111221 拆成后面的表达式即可: 111, 22, 1 其中有 3个one , 2个two, 1个one ,读起来就是: 312211

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string a="1";
 5         if(n==1) return a;
 6         for(int i=2;i<=n;i++)
 7         {
 8             string b;
 9             char current = a[0];
10             int j=1,count=1;
11             for(j=1;j<a.size();j++)
12             {
13                 if(a[j]==current)
14                 {
15                     count++;
16                 }
17                 else
18                 {
19                     char c = count +0;
20                     b+=c;
21                     b+=current;
22                     current = a[j];
23                     count=1;
24                 }
25             }
26             char c = count+0;
27             b+=c;
28             b+=current;
29             a= b;
30         }
31         return a;
32     }
33 };
bubuko.com,布布扣

转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢

LeetCode: Count and Say 题解,布布扣,bubuko.com

LeetCode: Count and Say 题解

原文:http://www.cnblogs.com/double-win/p/3781423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!