Count and Say

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.

分析:Count and Say的意思就是对于(n-1)th string,从左到右,count连续相同数字并且say,所以解决此问题的关键是得到第(n-1)个string,并且从左到右统计连续相同数字的个数并将结果存储在一个string中。代码如下:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string result = "1";
 5         
 6         for(int i = 2; i <= n; i++){
 7             string tmp = "";
 8             int count = 0;
 9             for(int j = 0; j < result.length(); j++){
10                 count++;
11                 if(j + 1 == result.length() || result[j] != result[j+1]){//when next is end or next is not same as current character
12                     tmp += std::to_string(count);
13                     tmp.push_back(result[j]);
14                     count = 0;
15                 }
16             }
17             result = tmp;
18         }
19         
20         return result;
21     }
22 };

 

posted on 2014-08-13 12:54  Ryan-Xing  阅读(422)  评论(0编辑  收藏  举报