# LeetCode: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.

......

 1 class Solution {
2 public:
3     string countAndSay(int n) {
4         if(n < 1)return "";
5         string prev = "1";
6         for(int i = 2; i <= n; i++)
7         {
8             char curChar = prev[0];
9             int times = 1;//curChar 出现的次数
10             string tmpstr;
11             prev.push_back('#');//处理边界条件
12             for(int k = 1; k < prev.size(); k++)
13             {
14                 if(prev[k] == curChar)
15                     times++;
16                 else
17                 {
18                     tmpstr += to_string(times);
19                     tmpstr.push_back(curChar);
20                     curChar = prev[k];
21                     times = 1;
22                 }
23             }
24             prev = tmpstr;
25         }
26         return prev;
27     }
28 };

【版权声明】转载请注明出处：http://www.cnblogs.com/TenosDoIt/p/3776356.html

posted @ 2014-06-08 16:12  tenos  阅读(7007)  评论(0编辑  收藏  举报