跳过正文
  1. leetcode 题解/

38_外观数列

·145 字·1 分钟

类型:字符串

    1. 外观数列 💚

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

    ❓ 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。

    比如,前五个外观

    1.     1
    2.     11
    3.     21
    4.     1211
    5.     111221
    第一项是数字 1 
    描述前一项这个数是 1     1 ”,记作 "11"
    描述前一项这个数是 11     1  记作 "21"
    描述前一项这个数是 21     2 +   1  记作 "1211"
    描述前一项这个数是 1211     1 +   2 +   1  记作 "111221"

    💡 递归模拟

    class Solution:
        def doCountAndSay(self, inStr: str) -> str:
            if not inStr:
                return ""
    
            outStr = ""
            lastChar = inStr[0]
            count = 1
            for c in inStr[1:]:
                if c == lastChar:
                    count += 1
                else:
                    outStr = outStr + str(count) + lastChar
                    lastChar = c
                    count = 1
            outStr = outStr + str(count) + lastChar
            return outStr
    
        def countAndSay(self, n: int) -> str:
    
            if n == 1:
                return "1"
            else:
                return self.doCountAndSay(self.countAndSay(n-1))