题目:
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.
思路:给你一个字符串,按照规则计算下一个字符串。
设置初始值后,迭代n-1次即可。
代码如下:
class Solution {
public:
string countAndSay(int n)
{
if(n == 0)
return "";
else if(n == 1)
return "1";
string str = "1";
n--;
while(n--)
{
str = count(str);
}
return str;
}
string count(string str)
{
int i = 0;
int n = str.size();
int count = 1;
int ch = str[0];
char str_count[10];
string result;
for(i = 1;i<n;i++)
{
if(str[i] == ch)
{
count++;
}
else
{
sprintf(str_count,"%d",count);
result += str_count;
result += ch;
ch = str[i];
count = 1;
}
}
sprintf(str_count,"%d",count);
result += str_count;
result += ch;
return result;
}
};