-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0038_count_and_say.py
More file actions
42 lines (36 loc) · 1.17 KB
/
0038_count_and_say.py
File metadata and controls
42 lines (36 loc) · 1.17 KB
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
38
39
40
41
42
class Solution:
def countAndSay(self, n: int) -> str:
# Base Case: 1
# 2 = "11", 3 = "21", 4 = "1211", 5 = "111221"
def countCon(num: str) -> str:
i = 0
cons = ""
latest = ""
count = 0
# Count number of consecutives
for char in num:
# First consecutive
if (latest == ""):
latest = char
count += 1
else:
# If consecutive
if (latest == char):
count += 1
# If not consecutive
else:
cons += str(count) + latest
latest = char
count = 1
cons += str(count) + latest
return cons
# None Case
if (not n or n <= 0):
return ''
# Base Case
if (n == 1):
return '1'
# Recursive Case
else:
# Count consecutives
return countCon(self.countAndSay(n - 1))