38.leetcode題目講解(Python): 報數

題目如下:


解題思路:比較簡單的題目,我使用二維數組來記錄數字出現的個數

參考代碼如下,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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章