-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount-and-Say.py
37 lines (34 loc) · 874 Bytes
/
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
37
#Iterative
class Solution:
def countAndSay(self, n):
ret = "1"
for _ in range(n-1):
ret = self.nextStep(ret)
return ret
def nextStep(self,prev):
res = ""
i = 0
while(i<len(prev)):
c = 1
while (i+1)<len(prev) and prev[i]==prev[i+1]:
i = i+1
c = c+1
res = res+str(c)+prev[i]
i = i+1
return res
#Reursive
class Solution:
def countAndSay(self, n: int) -> str:
if n==1:
return "1"
prev = self.countAndSay(n-1)
res = ""
i = 0
while(i<len(prev)):
c = 1
while (i+1)<len(prev) and prev[i]==prev[i+1]:
i = i+1
c = c+1
res = res+str(c)+prev[i]
i = i+1
return res