1446.连续字符

原题

一、遍历

一次遍历,用一个计数器cnt记录当前连续字符长度,每次s[i]s[i-1]比较,若相等则cnt++,否则cnt置1。每次得到新的cnt更新全局最大长度res

class Solution:
    def maxPower(self, s: str) -> int:
        n = len(s)
        if n == 1:
            return 1
        cnt = 1
        res = 0
        for i in range(1, n):
            if s[i-1] == s[i] :
                cnt += 1
            else:
                cnt = 1
            res = max(res, cnt)
        return res

最后更新于