leetcood学习笔记-38-报数
---恢复内容开始---
题目描述:
第一次提交:
class Solution: def countAndSay(self, n: int) -> str: f = "1" for i in range(n-1): count = 0 c = '' for j in range(len(f)): if j == 0 or (j - 1 > -1 and f[j]==f[j-1]): count += 1 else: c += str(count) + f[j - 1] count = 1 c += str(count) + f[j] i += 1 f = c; return f
方法二:递归
def countAndSay(self, n: int) -> str: def count(n, str_num): if n <= 1: return str_num new_str_num = "" cnt, old = 1, str_num[0] for ch in str_num[1:]: if ch != old: new_str_num += str(cnt) + old cnt, old = 1, ch else: cnt += 1 if cnt: new_str_num += str(cnt) + str_num[-1] return count(n-1, new_str_num) return count(n, "1")