38.leetcode题目讲解(Python): 报数

题目如下:


38.leetcode题目讲解(Python): 报数_第1张图片
题目

解题思路:比较简单的题目,我使用二维数组来记录数字出现的个数

参考代码如下,beats 86%

class Solution:
    def count(self, snum):
        num_count = []
        before = ""
        for s in snum:
            if s != before:
                num_count.append(["1" + s])
                before = s
            else:
                # print(num_count[-1][0][0])
                num_count[-1] = [str(int(num_count[-1][0][0]) + 1) + s]
        res = ""
        for n in num_count:
            res = res + n[0]
        return res

    def countAndSay(self, n):
        '''
        :type n: int
        :rtype: str
        '''
        i = 1
        snum = "1"
        while i < n:
            snum = self.count(snum)
            i += 1
        return snum

源码地址:
https://github.com/jediL/LeetCodeByPython

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)

你可能感兴趣的:(38.leetcode题目讲解(Python): 报数)