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;
}
};