美文网首页
[leetcode]报数

[leetcode]报数

作者: 5539 | 来源:发表于2018-10-29 10:57 被阅读9次

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:

  1. 1
    
  2. 11
    
  3. 21
    
  4. 1211
    
  5. 111221
    

1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。

给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。

注意:整数顺序将表示为一个字符串。

python解法

class Solution:
    def countAndSay(self, n):
        # Write your code here
        string = '1'
        for _ in range(n-1):
            count = 0
            temp = string[-1]
            result = ''
            for i in range(len(string)-1, -1, -1):
                if temp == string[i]:
                    count += 1
                else:
                    result = str(count) + temp + result
                    temp = string[i]
                    count = 1
            string = str(count) + temp + result
        return string

错误的python解法

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        string = '1'
        for i in range(n-1):
            count = 0
            temp = string[0]
            res = ''
            for j in range(len(string)-1):
                if temp == string[j]:
                    count += 1
                else :
                    res += str(count)+temp
                    temp = string[j]
                    count=0
            string = res
        return string

a = Solution()
print(a.countAndSay(5))

这种会报错temp=string[0] index out of range
有没有大佬可以教教我是为啥的哇

相关文章

  • [leetcode]报数

    报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1 11 21 1211 11...

  • leetcode 报数

    报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1 11 21 1211 11...

  • leetcode 38.报数 讲解

    LeetCode 38. 报数 链接https://leetcode-cn.com/problems/count-...

  • [LeetCode]38、报数

    题目描述 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1 11 21 12...

  • Leetcode-报数

    0.题目 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。 输入输出报数写作11一个一1121...

  • leetcode-报数

    报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1 被读作 "one 1" ...

  • leetcode38. 报数

  • Leetcode-38-报数

    题目 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1、12、113、214...

  • LeetCode038 报数

    题目: 思路: 1:当它是1的时候,我们就返回字符串'1'(1) 2:当它是2的时候,我们就对n=== 1报数,即...

  • LeetCode38.报数

    报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1 11 21 1211 11...

网友评论

      本文标题:[leetcode]报数

      本文链接:https://www.haomeiwen.com/subject/ljxbtqtx.html