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])

你可能感兴趣的:(2018-11-08)