38. Count and Say

 

1.     1
2.     11
3.     21
4.     1211
5.     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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

 

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"


思路:

n=1时输出字符串1;

n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;

n=3时,由于上次字符是11,有2个1,所以输出21;

n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。

 

 1 class Solution {
 2 public:
 3    string countAndSay(int n) {
 4         string res = "1";
 5 
 6         for (int i = 2; i <= n; i++)
 7             res = countsay(res);
 8         return res;
 9         }
10     
11     string countsay(string vec){
12         
13         string res;
14         char key = vec[0];
15         int cnt = 1;
16         if (vec == "1")
17             return "11";
18 
19         for (int i = 1; i<vec.size(); i++)
20         {    
21             if (key == vec.at(i)){
22                 cnt++;
23 
24             else
25             {
26                 res = res + to_string(cnt) + key;
27                 key = vec[i];
28                 cnt = 1;
29             }
30             if (i == vec.size()-1)
31                 res = res + to_string(cnt) + key;
32 
33         }
34 
35         return res;
36         
37     }
38 };

 

posted @ 2018-12-23 14:42  乐乐章  阅读(143)  评论(0编辑  收藏  举报