38. Count and Say

3,692次阅读
没有评论

共计 784 个字符,预计需要花费 2 分钟才能阅读完成。

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 where 1 ≤ n ≤ 30, 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"

解法

class Solution:
    def countAndSay(self, n) :
        
        if n==1:   
            return '1'
        elif n==2:
            return '11'
        data=self.countAndSay(n-1)
        count=dict()
        result=''
        tmp_char=''
        for x in range(len(data)):
            if not tmp_char:
                tmp_char=data[x]
                count[data[x]]=1
                continue
            if data[x]==tmp_char:
                count[data[x]]+=1
            else:
                result+=str(count[tmp_char])+tmp_char
                tmp_char=data[x]
                count[data[x]]=1
            if x==len(data)-1 :
                 result+=str(count[tmp_char])+tmp_char
          
        return result
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-02-13发表,共计784字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码