Leetcode 38:报数(超详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/84869103

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

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 项。

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

示例 1:

输入: 1
输出: "1"

示例 2:

输入: 4
输出: "1211"

解题思路

没有任何需要思考的地方,我们直接按照题目的意思来即可(记录数字出现的次数,然后刷新)。

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 0:
            return ''
        
        res = '1'
        while n != 1:
            res_len, i = len(res), 1
            tmp = ''
            while i <= res_len:
                count = 1
                while i < res_len and res[i] == res[i-1]:
                    count += 1
                    i += 1
                tmp += str(count) + str(res[i-1])
                i += 1
            res = tmp
            n -= 1
            
        return res

如果你对python非常熟悉的话,这里使用itertools.groupby应该是一个不错的选择。

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        s = '1'
        for _ in range(n - 1):
            s = ''.join(str(len(list(group))) + digit
                        for digit, group in itertools.groupby(s))
        return s

reference:

https://leetcode.com/problems/count-and-say/discuss/15999/4-5-lines-Python-solutions

扫描二维码关注公众号,回复: 4405273 查看本文章

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/84869103