题目如下:
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, 11, 21, 1211, 111221, …
数的规律如下:
1 读作 “one 1”,转化为数字为11,为第二个数;
11 读作“two 1”,转化wie数字为21,为第三个数;
21 读作“one 2, one 1”,转化为数字为1211,为第四个数;
1211 读作“one 1, one 2, two 1”,转化为数字为111221,为第五个数;
111221 读作“three 1, two 1, one 1”,转化为数字为312111,为第六个数
…..
要求输如一个数n,输出序列的第n个数。
从以上的规律可知,我们只需求出在第i个数中某个数连续出现的次数即可,便可得到第i+1个数,规律比较简单。
代码如下:
int findSeqLen(string &str, int index) {
int seq_len = 1;
for(int i = index + 1; i < str.size(); ++i)
if(str[i] == str[index]) ++seq_len;
else break;
return seq_len;
}
string countAndSay(int n) {
string result = "1";
if(n <= 0) return "";
for(int i = 2; i <= n; ++i) {
string new_str;
for(int j = 0; j < result.size(); ) {
int seq_len = findSeqLen(result, j);
new_str += seq_len + '0';
new_str += result[j];
j += seq_len;
}
result = new_str;
}
return result;
}