Count and Say

Count and Say

groupby Version - 40ms

1
2
3
4
5
6
7
8
9
10
11
import itertools
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
ret = '1'
for _ in range(n - 1):
ret = ''.join(str(len(list(group))) + digit for digit, group in itertools.groupby(ret))
return ret

Prev Version - 52ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
ret = '1'
for _ in range(n - 1):
prev = ret
ret = ''
j = 0
while j < len(prev):
cur = prev[j]
cnt = 1
j += 1
while j < len(prev) and prev[j] == cur:
cnt += 1
j += 1
ret += str(cnt) + str(cur)
return ret

test code

1
2
In [472]: s = Solution(); t = s.countAndSay(8); print(t)
1113213211

leet code