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.
n=1时,输出字符串为1
n=2时,输出字符串为11(表示前一个字符串中有1个1)
n=3时,输出字符串为21(表示前一个字符串中有2个1)
n=4时,输出字符串为1211(表示前一个字符串中有1个2,1个1)
....
可以发现输出结果是前一个字符串的各个数字字符的个数(个数+字符)
class Solution {
public:
string countAndSay(int n) {
string tmp="1";
for(int i=1;i<n;i++)
{
string stmp="";
for(int j=0;j<tmp.size();j++)
{
int k=j+1;
while(k<tmp.size()&&tmp[j]==tmp[k]) k++;
stringstream stream;
stream<<(k-j);
string ss;
stream>>ss;
stmp+=ss;
stmp+=tmp[j];
j=k-1;
}
tmp=stmp;
}
return tmp;
}
};