Leetcode 報數

# Leetcode 報數
# 有點難 我還是解決了 沒用什麼高深的算法 迭代的話,注意邊界情況的處理吧,就是最後一個pair 計數別忘記還有就是與倒數第二不一樣的話,額外考慮+1 
class Solution:
    def countAndSay(self, n: int) -> str:
        if n == 1:
            return "1"
        elif n == 2:
            return "11"
        elif n == 3:
            return "21"
        else:
            say = "21"
            new_say = ""
            count_sum = 4
            while count_sum <= n:
                j = 0
                count = 1
                while j + 1 < len(say):
                    if say[j] != say[j + 1]:
                        if count > 1:
                            new_say = new_say + str(count) + say[j]    
                            count = 1
                        else:
                            new_say = new_say + "1" + say[j]
                    else:
                        count += 1
                    j += 1
                # process the last pair
                if count > 1:
                    new_say = new_say + str(count) + say[-1]
                if say[-1] != say[-2]:
                    new_say = new_say + "1" + say[-1]
                say = new_say
                new_say = ""
                count_sum += 1
                
            return say
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章