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是第二个数字,输出第n个数字。
class Solution {
public:
string countAndSay(int n) {
string temp,result;
result.push_back('1'); //字符串result后面添加1;
int count;
char pre;
for(int i=1;i<n;i++){ //n为2时,只要进行一次,输出11;
temp=result;
result.clear();
pre=temp[0];
count=1;
for(int j=1;j<temp.size();j++){
if(temp[j]==pre)
count++;
else{ //temp[j]与之前的pre不相等,更行results,并把pre移到temp[j]处,打印出tem[j]之前的。
result.push_back('0'+count);
result.push_back(pre);
pre=temp[j];
count=1;
}
}
result.push_back('0'+count);//添上最后一个结束符
result.push_back(pre);
}
return result;
}
};