2018-11-08

leetcode

38.Count and Say

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 nwhere 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:1Output:"1"

Example 2:

Input:4Output:"1211"

题目分析:这道题目给定我们一个数字n,读出n的要出序列,也即是说当给定n的时候,读取n-1中的统计从左到右数值相同的个数,例如在给定4,n-1为3,在3中从左到右依次是1个2,1个1,所以结果为1211

斌是这么想的,给定数值n,我们依次从小到大遍历统计出各个数值,到最后循环结束即为所求值,直接上代码

class Solution:

    def countAndSay(self,n):

        """

        :type n: int

        :rtype: str

        """

        result = []#临时存储每个数值的结果

        temp = [1,1]

        count = 1

        if n == 1:

            return '1'

        if n == 2:

            return '11'

        for i in range(3, n + 1):#从3开始依次从小到大开始遍历

            count = 1#每次循环计数要清空

            lenth = len(temp)

            for j in range(1, lenth):

                if temp[j] == temp[j - 1]:

                    count += 1

                elif temp[j] != temp[j - 1]:

                    result.append(count)

                    result.append(temp[j - 1])

                    count = 1

            result.append(count)

            result.append(temp[j])

            temp = result

            result = []

        return ''.join([str(i) for i in temp])

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 8,695评论 0 2
  • Ymnunu阅读 2,144评论 1 2
  • 无论世界上多么有名的老师都不及大自然这个“老师”厉害,它从很多事物上给了我们很多重要的启示。下面就来讲一讲害羞草带...
    D030鱼佛山阅读 3,496评论 0 1
  • 有一种爱叫做:你飞的再远,都离不开我的怀抱。 三岁那年,父亲赶着牛车去赶集,我就被放在牛车里面的被...
    冯振虎阅读 1,872评论 0 2
  • 下午出去田埂上转悠,看到两个老街坊抬个阖子,以为是给谁家送喜的,上前一问,原来是我们家隔壁邻居死了。离这么近竟然没...
    我就是女神阅读 1,183评论 2 0