题目:
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 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"
其实很简单,这个结构很迭代啊,就是输入‘1’,输出‘11’,‘11’第一个1表示个数,第二个1表示‘1’,就是说有1个字符1,输入‘1211’,输出‘111221’,表示有1个1,1个2,2个1
现在上代码+调试:(之前有点不懂,借鉴了其他博主)
class Solution(object):
def countAndSayF(self,s):
count = 0
ans = ''
tmp = s[0]
for n in range(len(s)):
if s[n]==tmp:
count+=1
else:
ans += str(count)+tmp
tmp = s[n]
count = 1
ans += str(count)+tmp
return ans
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
ans = '1'
while n>1:
ans = self.countAndSayF(ans)
n-=1
return ans
a = Solution()
print a.countAndSay(5)