leetcode 424. 替换后的最长重复字符 python双指针

给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。

注意:字符串长度 和 k 不会超过 104。

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        n = len(s)  # 字符串长度
        left, right = 0, 0  # 左右指针
        counter = {
     }  # 统计左右指针中间每个字母的出现次数
        res = 0

        while right < n:
            if s[right] in counter:  #在统计次数里加上指向的
                counter[s[right]] += 1
            else:
                counter[s[right]] = 1

            maxchar = sorted(counter, key=lambda x: counter[x])[-1]  #算出出现次数最多的字母

            #判断左右指针中间的长度是否超过了替换字符后可产生的连续字符串(换完后左右指针中间还有别的字符)
            while right - left + 1 > counter[maxchar] + k:  
                counter[s[left]] -= 1  #右移左指针
                left += 1
                maxchar = sorted(counter, key=lambda x: counter[x])[-1]
                
            res = max(res, right-left+1)  #修改res
            right += 1  #右移右指针
        return res

你可能感兴趣的:(leetcode)