-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path38_Count_and_Say.py
36 lines (34 loc) · 940 Bytes
/
38_Count_and_Say.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
# Recursive
def countAndSay(self, n: int) -> str:
if n == 1:
return "1"
prev = self.countAndSay(n-1)
ns = ""
count = 1
for i in range(len(prev)-1):
if prev[i] == prev[i+1]:
count+=1
else:
ns += str(count)+prev[i]
count = 1
ns += str(count)+prev[-1]
return ns
# Iterative
def countAndSay1(self, n: int) -> str:
result = "1"
if n == 1:
return "1"
while n > 1:
ns = ""
count = 1
for i in range(len(result)-1):
if result[i] == result[i+1]:
count+=1
else:
ns += str(count)+result[i]
count = 1
ns += str(count)+result[-1]
n-=1
result = ns
return result