38. 报数

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

解法一:迭代

每次看i和i+1是否相等

class Solution:
    def countAndSay(self, n: int) -> str:
        if n == 1:
            return '1'
        oldStr = '11'
        for _ in range(2, n):  #从第二轮开始迭代
            count = 1  #连续字符计数器
            newStr = ''  #新串
            for i in range(len(oldStr)-1):  #遍历旧串
                if  oldStr[i] == oldStr[i+1]:  #检测到连续字符,count加1
                    count += 1
                else:  #否则将之前累计的结果写入新串,计数器重置
                    newStr += str(count) + oldStr[i]
                    count = 1          
            newStr += str(count) + oldStr[-1]  #对最后一位,特殊处理
            oldStr = newStr    #更新旧串
        return oldStr

最后更新于