The count-and-say sequence is the sequence of integers beginning as follows:
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, generate the nth sequence.
思路:一个个迭代,没毛病。。。
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
i=1;r='1'
while i<n:
r = self.next(r);i+=1
return r
def next(self,s):
cnt=0;last='-1';r=''
for i in s:
if last=='-1':
cnt+=1;last = i
elif i==last:
cnt+=1
else:
r+=str(cnt)+last
cnt=1;last=i
r+=str(cnt)+last
return r