The count-and-say sequence is the sequence of integers with the first five terms as following:
-
1
-
11
-
21
-
1211
-
111221
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: “1”
Example 2:
Input: 4
Output: “1211”
code
class Solution:
def count(x):
return output
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
d = {}
d[1] = str(1)
for i in range(2, n+1):
count = []
index = []
count.append(1)
output = ''
for j in range(1, len(d[i -1])):
if d[i -1][j] == d[i -1][j - 1]:
count.append(count[j - 1] + 1)
else:
count.append(1)
index.append(j-1)
index.append(len(d[i -1]) - 1)
for k in index:
output += str(count[k])
output += d[i -1][k]
d[i] = output
return d[n]
tips
if d[i -1][j] == d[i -1][j - 1]:
count.append(count[j - 1] + 1)
else:
count.append(1)
index.append(j-1)
index.append(len(d[i -1]) - 1)
for k in index:
output += str(count[k])
output += d[i -1][k]
相当于一个计算count和对应数字的function