lintcode python代码 420 报数

报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:

1, 11, 21, 1211, 111221, …

1 读作 “one 1” -> 11.

11 读作 “two 1s” -> 21.

21 读作 “one 2, then one 1” -> 1211.

给定一个整数 n, 返回 第 n 个顺序

思路:数字不好处理位数,将其变为字符串。从后往前读,记最后一个temp = string[-1],相同+1。不同result = str(count) + temp + result temp = string[i] count = 1

class Solution:
    # @param {int} n the nth
    # @return {string} the nth sequence
    def countAndSay(self, n):
        # Write your code here
        string = '1'
        for _ in range(n-1):
            count = 0
            temp = string[-1]
            result = ''
            for i in range(len(string)-1, -1, -1):
                if temp == string[i]:
                    count += 1
                else:
                    result = str(count) + temp + result
                    temp = string[i]
                    count = 1
            string = str(count) + temp + result
        return string
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值