Count and Say in python

问题链接:

https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/886/

解题思路:

递归

遇到难题:

原始思路是直接使用dictionary记录数字出现的次数,后来发现dictionary不能保证次序。

抛弃上面思路,直接用count

最终解法如下:

class Solution(object):
def countAndSay(self, n):
    """
    :type n: int
    :rtype: str
    """
    if n < 0:
        return ""
    elif n == 1:
        return "1"
    else:
        s = self.countAndSay(n - 1)
        result = []
        tmp = s[0]
        count = 0
        for i in range(len(s)):
            if s[i] == tmp:
                count += 1
            else:
                result.append(str(count))
                result.append(tmp)
                count = 1
                tmp = s[i]
        result.append(str(count))
        result.append(tmp)
        return ''.join(result)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,392评论 2 36
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,927评论 0 33
  • 个人笔记,方便自己查阅使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik阅读 67,949评论 0 5
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,146评论 0 23
  • 寂寞难耐(老李啊,你真行) 寂寞难耐 总是平白无故的.难过起来 然而大夥都在笑话正是精彩 怎麽好意思.一个人走开 ...
    haore147阅读 366评论 0 2

友情链接更多精彩内容