Leetcode 38. 數數並說

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        S="1"
        for i in range(1,n): #控制外層的迭代次數
            S=self.myfun(S)
        return S

    def myfun(self,S):
        res=""
        dict={}
        for s in S:
            if len(dict) is 0:#空時直接插入鍵與值
                dict[s]=1

            else: #這裏又要分兩種情況,一種是沒有同名的存在,就要彈出並做處理  ;若已存在,則自增1
                if s not in dict.keys():
                    name = list(dict.keys())[0]
                    count = dict[name]
                    res += str(count) + str(name)
                    del dict[name]
                    dict[s] = 1
                else:
                    dict[s]+=1
        if len(dict) is 1:     #最後將剩餘的一對鍵與值進行處理
            name = list(dict.keys())[0]
            count = dict[name]
            res += str(count) + str(name)
        return res

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