Leetcode刷题记录——38. 外观数列

在这里插入图片描述
本题的任务,实质上是
对于一个由数字组成的字符串
我们按将其中相邻且相等的区段分割,然后对每个区段输出两个数,一个是重合的数字,一个是重合的长度

class Solution:
    def countAndSay(self, n: int) -> str:
        #根本任务:将上一个字符串分割
        #分割标准为 相邻值若相等 则分到一组
        newdict = {
            1:'1',
            2:'11',
            3:'21',
            4:'1211',
            5:'111221'
        }
        if n <= 5:
            return newdict[n]
        i = 5
        last = newdict[5]
        while i < n:
            last = self.each(last)
            i += 1
        return last
    def each(self,inputstr):
        res = ''
        isvoid = True
        times = 0#1
        value = 0#inputstr[0]
        length = len(inputstr)
        #tempres = 0#inputstr[0]
        for i in range(length):
            if isvoid:
                times = 1
                value = inputstr[i]  
                isvoid = False  
            elif inputstr[i] == value:
                times += 1
            elif inputstr[i] != value:
                res += str(times)
                res += str(value)
                value = inputstr[i]
                times = 1
        res += str(times)
        res += str(value)
        return res


发布了59 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/105479864