题目大意:给出一个数字n,按照下面的规律生成第n个字符串序列
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
.
1.如何n=1时直接返回“1”或者n=2时返回“11”
2.初始化 str=="11"则将n的规模缩小2.
3.设置计数器ct=1结果字符串res,遍历字符串如何str[i]==str[i+1]则将计数器加1,否则将计数器和当前字符加入结果中。(为了使操作统一对于每个str再其末尾加‘0’)
4.用当前结果迭代str直至n为0.
5.返回生成的字符串序列。
代码如下:
class Solution {
public:
string countAndSay(int n) {
if(n==1) return "1";
if(n==2) return "11";
string res,str="11";
n-=2;
while(n--){
str+='0';
int ct=1;
for(int i=0;i<str.length()-1;++i){
if(str[i]==str[i+1])
ct++;
else {
res+=ct+'0';
res+=str[i];
ct=1;
}
}
str=res;
res.clear();
}
return str;
}
};