LeetCode题解(0038):生成外观数列(Python)
发布日期:2021-06-29 19:51:44 浏览次数:3 分类:技术文章

本文共 1487 字,大约阅读时间需要 4 分钟。

题目:(简单)

标签:字符串

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( 2 N ) O(2^N) O(2N) O ( N ) O(N) O(N) 36ms (97.26%)
Ans 2 (Python) O ( 2 N ) O(2^N) O(2N) O ( N ) O(N) O(N) 48ms (59.31%)
Ans 3 (Python) O ( 1 ) O(1) O(1) O ( 1 ) O(1) O(1) 36ms (97.26%)

解法一(循环处理):

def countAndSay(self, n: int) -> str:    def count(s):        new = ""        last = None        num = 0        for c in s:            if c != last:                if num > 0:                    new += str(num) + last                last = c                num = 1            else:                num += 1        if num > 0:            new += str(num) + last        return new    s = "1"    for i in range(1, n):        s = count(s)    return s

解法二(递归实现):

def countAndSay(self, n: int) -> str:    def count(s):        new = ""        last = None        num = 0        for c in s:            if c != last:                if num > 0:                    new += str(num) + last                last = c                num = 1            else:                num += 1        if num > 0:            new += str(num) + last        return new    def get_num(n):        if n == 1:            return "1"        else:            return count(get_num(n - 1))    return get_num(n)

解法三(枚举法):

class Solution:    def countAndSay(self, n: int) -> str:        count_dict = {
1: '1', 2: '11', 3: '21', 4: '1211', 5: '111221', 6: '312211', 7: '13112221', 8: '1113213211', 9: '31131211131221', 10: '13211311123113112211',......} return count_dict[n]

转载地址:https://dataartist.blog.csdn.net/article/details/106761010 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(0053):求具有最大和的连续子数组(Python)
下一篇:LeetCode题解(0035):计算向有序列表中插入指定数据的位置(Python)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月07日 08时33分53秒