leetcode--38. 数数并说

浪子不回头ぞ 提交于 2019-12-08 06:52:03

题目:38. 数数并说

链接:https://leetcode-cn.com/problems/count-and-say/description/

一个序列,第一项是1,我们读作1个1,于是下一项就是11。第二项不是11嘛,读作2个1,于是第三项是21,读作1个2,1个1,于是第四项是1211,这个又读作1个1,1个2,2个1,于是下一项就是111221...略略略...

python:

def getNext(s):
    s = list(str(s))
    temp, cnt, res = -1, 1, ""
    for num in s:
        if num == str(temp):
            cnt += 1
        else:
            if temp != -1:
                res += (str(cnt) + str(temp))
            temp, cnt = num, 1
    res += (str(cnt) + str(temp))
    return res

class Solution:
    ans = ["1"]
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        while len(self.ans)<n:
            self.ans.append(getNext(int(self.ans[-1])))
        return self.ans[n-1]

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!