LeetCode 筆記 - 38. Count and Say

題目在此 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

也許你也會想看看