[LeetCode38] 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.

分类:String

代码:

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

 

posted @ 2016-08-09 23:31  zhangbaochong  阅读(183)  评论(0)    收藏  举报