The count-and-say sequence is the sequence of integers with the first five terms as following:
1 11 21 1211 1112211 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次就能得到我们想要的结果。
class Solution { private: string Count(string s) { string r; int i=0; int c; while (i < s.size()) { c = 1; char t; if (s[i] == s[i + 1]) { while (s[i] == s[i + 1]) { c++; i++; } t = c + '0'; r = r + t + s[i]; i++; } else { t = '1'; r = r + t + s[i]; i++; } } return r; } public: string countAndSay(int n) { if (n == 1) return "1"; string s = "1"; while (--n) { s = Count(s); } return s; } };