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>
本文详细解析了Count-and-Say序列的生成原理及其实现过程,通过迭代计算每一步序列的读取规则,最终生成指定位置的序列。重点在于理解序列的构造逻辑,并通过代码实现来验证算法的有效性。
493

被折叠的 条评论
为什么被折叠?



