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.
这个题的描述有点迷惑性,而且这还是有过更正的,我看discuss上有人讨论说之前更误导人。只看前五个例子,还是有可能理解错,正确的第6的sequence:312211。现在我们理解这个题的意思了,“个数”+“数字”组合起来,实现上从低到高迭代生成就行了。
<span style="color:#333333;">class Solution {
public:
string countAndSay(int n) {
string ans="1";
if(n==1) return ans;
//string ans=last;
for(int i=2;i<=n;i++){
string temp;
int m=0,n=0;
while(n!=ans.size()){
if(ans[n]==ans[m]&&n==(ans.size()-1)){</span><span style="color:#cc0000;">temp+=std::to_string(n-m+1)+ans[m]</span><span style="color:#333333;">;n++;}
else if(ans[n]==ans[m]&&n!=(ans.size()-1)){
n++;
}else{
</span><span style="color:#ff0000;">temp+=std::to_string(n-m)+ans[m];</span><span style="color:#333333;">
m=n;
}
}
ans=temp;
}
return ans;
}
};</span>