LeetCode 之 Count and Say

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值