38. Count and Say

来源:互联网 发布:怎样评价日剧 知乎 编辑:程序博客网 时间:2024/06/17 14:39

题意:The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.

思路:这题貌似很难找到什么规律,直接生成吧

class Solution(object):    def countAndSay(self, n):        """        :type n: int        :rtype: str        """        ans= "1"        for i in xrange(n-1):            cnt, index= 1, len(ans)            for j in xrange(len(ans)):                if j+1<index and ans[j]==ans[j+1]:                    cnt+=1                else:                    ans+=str(cnt)+str(ans[j])                    cnt = 1            ans = ans[index:]        return ans
0 0