类型:字符串
-
- 外观数列 💚
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))