Count and Say

本文介绍了一个有趣的数列问题——Count and Say,并分别用C++和Python两种语言实现了该问题的解决方案。Count and Say数列是这样定义的:以数字1开始,之后每一项都是对前一项的描述。例如第一项为1,第二项是对1的描述“1个1”,即11,第三项是对11的描述“2个1”,即21。

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

c++

class Solution {
public:
    string countAndSay(int n) {
        if (n < 0) return "";
        string cur = "1";
        while (--n>0){
            int st = 0;
            int ed = 0;
            string tmp="";
            while (st<cur.size() && ed<cur.size()){
                int cnt = 0;
                while (ed<cur.size() && cur[st] == cur[ed]) {
                    cnt++;
                    ed++;
                }
                tmp.push_back(cnt + '0');
                tmp.push_back(cur[st]);
                st = ed;
                //ed = st;
            }
            cur = tmp;
        }
        return cur;
    }
};

python

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n <0: return 0
        cur = '1'
        while n>1:
            n -= 1

            tmp = []
            st,ed =0,0
            while st<len(cur) and ed<len(cur):
                cnt=0
                while ed<len(cur) and cur[st]==cur[ed]:
                    cnt += 1
                    ed += 1
                tmp.append(str(cnt))
                tmp.append(cur[st])
                st = ed
            cur = ''.join(tmp)
        return cur
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值