美文网首页
Count and Say in python

Count and Say in python

作者: 你过来啊2018 | 来源:发表于2018-02-14 16:03 被阅读0次

问题链接:

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)

相关文章

网友评论

      本文标题:Count and Say in python

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