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

描述的更清楚的版本:http://www.careercup.com/question?id=4425679

用模拟法:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         string s = "1";
 7         for(int i = 2; i <= n; i++)
 8         {
 9             string nextS;
10             char key = '-';
11             int j = 0;
12             int count = 0;
13             while(j < s.size())
14             {
15                 if (key == s[j])
16                     count++;
17                 else
18                 {
19                     if (key != '-')
20                     {
21                         nextS = nextS + (char)(count + '0');
22                         nextS = nextS + key;
23                     }
24                     
25                     key = s[j];
26                     count = 1;                    
27                 }
28                 
29                 j++;
30             }
31             nextS = nextS + (char)(count + '0');
32             nextS = nextS + key;
33             
34             s = nextS;
35         }
36         
37         return s;
38     }
39 };
posted @ 2012-10-31 11:12  chkkch  阅读(2443)  评论(0编辑  收藏  举报