LeetCode 筆記 - 38. Count and Say

針對 LeetCode 第 38 題「外觀數列」,本文教學如何根據規則進行字串編碼。解題核心在於準確描述上一個數列的組成情況,並轉換為新的字串表示。這是一篇掌握基礎字串遍歷、計數與模擬邏輯的實作隨筆。

發佈
閱讀
約 1 分鐘
字數
181
⚠️ 舊文提醒:本文發佈於約 4 年前,部分內容或指令可能已過時,請斟酌參考。

題目在此 38. Count and Say

輸入 n 請根據規則給出編碼後的結果

解題思維

沒啥特別的,就照著規則實作

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:

data = [None] * 32
data[1] = '1'

def countAndSay(self, n: int) -> str:
if self.data[n] is not None:
return self.data[n]

last_result = self.countAndSay(n - 1)

result = ''
while (size := len(last_result)) > 0:

count = 1
while count < size and last_result[count] == last_result[0]:
count += 1

result = f'{result}{count}{last_result[0]}'
last_result = last_result[count:]

self.data[n] = result

return result

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟