题目:38. 数数并说
链接:https://leetcode-cn.com/problems/count-and-say/description/
一个序列,第一项是1,我们读作1个1,于是下一项就是11。第二项不是11嘛,读作2个1,于是第三项是21,读作1个2,1个1,于是第四项是1211,这个又读作1个1,1个2,2个1,于是下一项就是111221...略略略...
python:
def getNext(s):
s = list(str(s))
temp, cnt, res = -1, 1, ""
for num in s:
if num == str(temp):
cnt += 1
else:
if temp != -1:
res += (str(cnt) + str(temp))
temp, cnt = num, 1
res += (str(cnt) + str(temp))
return res
class Solution:
ans = ["1"]
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
while len(self.ans)<n:
self.ans.append(getNext(int(self.ans[-1])))
return self.ans[n-1]