38. Count and Say

来源:互联网 发布:php 指定变量类型 编辑:程序博客网 时间:2024/06/05 12:10

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     12.     113.     214.     12115.     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.

有一个小技巧是 在字符串末尾加 一个星号,方便计数

class Solution(object):    def countAndSay(self, n):        if n == 1:            return "1"        if n == 2:            return "11"        result = self.countAndSay(n-1) + '*'        cnt = len(result)        s = ""        count = 1        for i in range(cnt-1):            if result[i] == result[i+1]:                count+=1            else:                s = s + str(count) + result[i]                count = 1        return s


原创粉丝点击