38. Count and Say

1,356次阅读
没有评论
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:

<b>Input:</b> 1
<b>Output:</b> "1"

Example 2:

<b>Input:</b> 4
<b>Output:</b> "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

admin
版权声明:本站原创文章,由admin2019-02-13发表,共计784字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)