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         string res = "1";
 5         for(int i = 2; i <= n; i++) {
 6             stringstream ss;
 7             int k = 1;
 8             for(int j = 1; j < res.size(); j++) {
 9                 if(res[j] == res[j-1]) k++;
10                 else if(res[j] != res[j-1]) {
11                     ss << k << res[j-1];
12                     k = 1;
13                 }
14             }
15             ss << k << res[res.size()-1];
16             ss >> res;
17         }
18         return res;
19     }
20 };

 

posted @ 2014-04-05 10:28  beehard  阅读(148)  评论(0编辑  收藏  举报