424. Longest Repeating Character

2021-02-02  本文已影响0人  morningstarwang

Ref: https://leetcode-cn.com/problems/longest-repeating-character-replacement/

这道题是经典的双指针滑动窗口问题,其核心思路如下:

代码如下:

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        s = [x for x in s]
        l = len(s)
        if l <= 1:
            return l
        left = 0
        right = 0
        freq = [0 for _ in range(26)]
        max_count = 0
        result = 0
        while right < l:
            freq[ord(s[right]) - ord('A')] += 1
            max_count = max(max_count, freq[ord(s[right]) - ord('A')])
            right += 1
            if right - left > max_count + k:
                freq[ord(s[left]) - ord('A')] -= 1
                left += 1
            result = max(result, right - left)
        return result
上一篇下一篇

猜你喜欢

热点阅读