【LEETCODE】38-Count and Say

来源:互联网 发布:淘宝赠运费险什么意思 编辑:程序博客网 时间:2024/06/01 09:22

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" or11.

11 is read off as "two 1s" or21.

21 is read off as "one 2, thenone 1" or1211.

Given an integer n, generate the nth sequence.

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


题意:

给 n,生成第 n 个 count-and-say 序列


count-and-say 序列:从左向右,数序列中的连续出现的数字的次数count及该数字


思路:

根据逻辑,从 1st 为 1 开始向下数

用 j 控制生成第 j 个 s,每个 s 都由上一个生成

用 a 纪录当前数字,用 c 纪录 a 出现的连续的次数

遇到不连续的数字时,将当前的 c a 纪录到 r,之后,a 更新 c 更新,直到全部数完





class Solution(object):    def countAndSay(self, n):        """        :type n: int        :rtype: str        """                if n==1:            return '1'                    s='1'                for j in range(2,n+1):         #j=n,生成第n个s            r=''            i=0            while i<len(s):                #i=0                #a=s[0]                a=s[i]                c=1                while i+1<len(s) and s[i+1]==s[i]:    #i=2,a=1,c=3                    c+=1                    i+=1                r+=str(c)               #临时纪录连续的 次数和当前字符                r+=str(a)                i+=1                    #i=3            s=r                                 return s



0 0
原创粉丝点击