Count and Say
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 n^{th} sequence.
Note: The sequence of integers will be represented as a string.
思路:
后一个数需要数前一数中各个数字的出现次数,并记录,
res.push_back(countnum+'0');//记录数字出现次数
res.push_back(temp);//记录该数字
class Solution {
public:
string say(string s){
string res;
char temp=s[0];
int countnum=1;
for(int i=1;i<s.length();i++)
{
if(s[i]==temp)
countnum++;
else
{
res.push_back(countnum+'0');
res.push_back(temp);
temp=s[i];
countnum=1;
}
}
res.push_back(countnum+'0');
res.push_back(temp);
return res;
}
string countAndSay(int n) {
string res="1";
for(int i=1;i<n;i++)
res=say(res);
return res;
}
};