题目翻译
一个”数和说(count and say)“序列是像这样的一个整数序列:1, 11, 21, 1211, 111221, …。
1 读作 “1个1” 或 11.
11 读作 “2个1” 或 21.
21 读作 “1个2,1个1” 或 1211.
给定整数n,生成第n个序列。
注意:整数序列用字符串表示。思路方法
这个问题重点首先是要读懂题目。然后在想这个过程的时候,你可能会想的比较复杂,比如,会不会出现连续十几个一样的数字,比如1111111111,读作“ten 1”,然后转换成101。实际上,有大神已经证明,这个序列里的数不会超过4。这边搬运了一下。
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = '1'
for i in xrange(n-1):
new_res = ''
j = 0
while j < len(res):
count = 1
while j < len(res)-1 and res[j] == res[j+1]:
j = j + 1
count = count + 1
j = j + 1
new_res = new_res + str(count) + res[j-1]
res = new_res
return res