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 n^th sequence.

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

 

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

 

posted on 2015-05-16 17:49  黄瓜小肥皂  阅读(128)  评论(0编辑  收藏  举报