#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Count and Say
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...求第n个序列
1 is read off as "one 1" or 11. 1个1,所以下一个为11
11 is read off as "two 1s" or 21. 2个1,所以下一个为21
21 is read off as "one 2, then one 1" or 1211.一个2一个1,所以下一个为1211
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
'''
class Solution(object):
def __countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
ret = [n[-1]]#最好用栈
times = 1
index = len(n) - 2
while index >= 0:
if n[index] == ret[0]:
times += 1
else:
ret.insert(0,times)
ret.insert(0,n[index])
times = 1
index -= 1
ret.insert(0,times)
return ret
def countAndSay(self,n):
if n == 0:
return ''
if n == 1:
return '1'
first = [1,1]
for i in range(n - 2):
#print first
first = self.__countAndSay(first)
return ''.join([str(i) for i in first])
if __name__ == "__main__":
s = Solution()
print s.countAndSay(3)
37 leetcode - Count and Say
最新推荐文章于 2024-07-22 16:27:42 发布