1.The count-and-say sequence is the sequence of integers with the first five terms as following:
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 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"
2.題目要求:求一個數組的第n項,而這個數組的通項公式可以理解成:
第1項:1
第2項:11
第3項:21
第4項:1211
第5項:111221
第6項:312211
...
第n項:第n-1項的數字串從左到右讀出來,比如說第2項是11,因為第1項是1,讀起來就是1個1,所以第2項的11前一個1表示后一個1的計數,以此類推。
3.方法:設計一個函數可以求出某數字串的下一個數字串,只要調用該函數n-1次就能得到我們想要的結果。
4.代碼:
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;
}
};