leetcode--38. 数数并说

本文详细解析了LeetCode上题目“数数并说”的算法实现,通过递归生成序列,介绍了如何读取每项内容并转换为下一序列的方法。使用Python语言实现了递归生成序列的功能。

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

题目:38. 数数并说

链接:https://leetcode-cn.com/problems/count-and-say/description/

一个序列,第一项是1,我们读作1个1,于是下一项就是11。第二项不是11嘛,读作2个1,于是第三项是21,读作1个2,1个1,于是第四项是1211,这个又读作1个1,1个2,2个1,于是下一项就是111221...略略略...

python:

def getNext(s):
    s = list(str(s))
    temp, cnt, res = -1, 1, ""
    for num in s:
        if num == str(temp):
            cnt += 1
        else:
            if temp != -1:
                res += (str(cnt) + str(temp))
            temp, cnt = num, 1
    res += (str(cnt) + str(temp))
    return res

class Solution:
    ans = ["1"]
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        while len(self.ans)<n:
            self.ans.append(getNext(int(self.ans[-1])))
        return self.ans[n-1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值