[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 say(string s) {
 4         string res;
 5         char tag = s[0];
 6         int count = 1;
 7         for (int i = 1; i <= s.length(); ++i) {
 8             if (s[i] == tag) {
 9                 ++count;
10             } else {
11                 res.push_back('0' + count);
12                 res.push_back(tag);
13                 tag = s[i];
14                 count = 1;
15             }
16         }
17         return res;
18     }
19     
20     string countAndSay(int n) {
21         string s;
22         if  (n == 0) return s;
23         s = "1";
24         for (int i = 1; i < n; ++i) {
25             s = say(s);
26         }
27         return s;
28     }
29 };

 

posted @ 2014-04-06 00:29  Eason Liu  阅读(198)  评论(0编辑  收藏  举报