Skip to content

Commit 000c7ef

Browse files
committed
Create 38. Count and Say.py
1 parent 832c1f1 commit 000c7ef

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: 38. Count and Say.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# -*- coding: utf-8 -*-
2+
# @Time : 2019/3/2 14:34
3+
# @Author : xulzee
4+
5+
# @File : 38. Count and Say.py
6+
# @Software: PyCharm
7+
class Solution:
8+
def countAndSay1(self, n: int) -> str:
9+
if n == 1:
10+
return "1"
11+
12+
result = self.countAndSay(n - 1)
13+
14+
i = result[0]
15+
count_i = 1
16+
temp = ""
17+
for j in range(1, len(result)):
18+
if result[j] == i:
19+
count_i += 1
20+
else:
21+
temp = temp + str(count_i) + str(i)
22+
count_i = 1
23+
i = result[j]
24+
temp = temp + str(count_i) + str(i)
25+
return temp
26+
27+
def countAndSay(self, n: int) -> str:
28+
if n == 1:
29+
return "1"
30+
if n == 2:
31+
return "11"
32+
pre = "11"
33+
for i in range(3,n+1):
34+
temp = ""
35+
count = 1
36+
count_char = pre[0]
37+
for j in range(1, len(pre)):
38+
if count_char == pre[j]:
39+
count += 1
40+
else:
41+
temp = temp + str(count) + str(count_char)
42+
count_char = pre[j]
43+
count = 1
44+
temp = temp + str(count) + str(count_char)
45+
pre = temp
46+
return pre
47+
48+
49+
50+
51+
if __name__ == '__main__':
52+
for n in range(1, 21):
53+
print(Solution().countAndSay(n))

0 commit comments

Comments
 (0)