⚡Flashcard Drill➔
NeetCode #231LC-424MediumSliding WindowBlind 75NC 150NC 250
← Back to All Problems

#231 · #424 · Longest Repeating Character Replacement(替换后的最长重复字符)

📌 Problem Statement & Constraints

You are given a string s and an integer k. You may replace at most k characters with any uppercase letter. Return the length of the longest substring containing the same letter after at most k replacements. Constraints: 1 <= s.length <= 10^5, 0 <= k <= s.length; s consists of uppercase letters.

💡 Core Algorithmic Approaches

  1. For a window, the number of replacements needed is window_length - max_frequency_in_window.
  2. Expand the window to the right, tracking the maximum character frequency inside it.
  3. When the required replacements exceed k, shrink from the left by one.
  4. Key trick: never decrease maxf. It only needs to be an upper bound, because the window size never needs to shrink below the best answer already found -- this keeps the algorithm a true single pass.

💻 Benchmark Python3 Implementation

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        from collections import Counter
        cnt = Counter()
        l = 0
        maxf = 0                       # max frequency seen in any window so far
        best = 0
        for r, ch in enumerate(s):
            cnt[ch] += 1
            maxf = max(maxf, cnt[ch])
            # window is valid when (length - maxf) <= k
            if (r - l + 1) - maxf > k:
                cnt[s[l]] -= 1
                l += 1
            best = max(best, r - l + 1)
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass with O(1) counter operations.
💾 Space Complexity
O(1): the counter holds at most 26 entries.

⚠️ Interview Pitfalls & Follow-ups

  • Decrementing maxf when shrinking: not only unnecessary but wrong for the standard formulation -- maxf is used as a monotone upper bound, and recomputing it exactly would cost O(26) per step and break the amortised argument.
  • Using a while loop to shrink until valid: it still works but is O(n) per step in the worst case if maxf is recomputed; with the monotone bound a single if suffices.
  • Forgetting that the answer is the window length, not the count of replacements: the window may not be fully uniform, but its length is what matters.
  • Assuming the replaced characters must all become the same letter: they do -- the target letter is the window's most frequent one.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

替换后的最长重复字符

给你一个字符串 s 和一个整数 k。你可以选择字符串中的任一字符,并将其更改为任何其他大写英文字母。该操作最多可执行 k 次。在执行上述操作后,返回包含 相同字母 的最长子字符串的长度。约束:1 ≤ s.length ≤ 10^5;s 仅由大写英文字母组成;0 ≤ k ≤ s.length。

核心要点

  • 滑动窗口 + 最大频次(标准解) :窗口内若「长度 − 出现最多的字符的频次 ≤ k」,则该窗口可以被改成全同字符,合法。
  • 维护 maxf :记录窗口内某字符的最大出现次数。当 (r − l + 1) − maxf &gt; k 时收缩左边界。
  • maxf 不需要在收缩时递减(关键优化) :因为我们只关心「最长的合法窗口长度」。 maxf 只会单调不减,若它偏大,窗口会显得「不够合法」,从而不更新答案——但历史最大值已被记录,不会影响正确性。
  • 为什么这个优化成立 :答案只增不减;当 maxf 偏大时窗口长度不会超过已记录的答案,因此跳过更新是安全的。

常见陷阱

  • 在收缩窗口时同步递减 maxf :那需要重新扫描窗口求最大频次,会退化为 O(n²)。标准做法是让 maxf 单调不减(见思路第 3 点)。
  • 判定条件写成 长度 − maxf &gt;= k :应为 &gt; k 。当差值恰好等于 k 时,可以把其他字符全部替换掉,窗口合法。
  • 误以为 maxf 必须精确对应当前窗口 :优化后 maxf 可能对应更早的窗口,但由于答案只增不减,不影响最终结果的正确性。
  • 忘记收缩窗口 :只扩不缩会让窗口无限增长,答案错误。

参考实现

from collections import defaultdict

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        cnt = defaultdict(int)
        l = 0
        maxf = 0                    # 窗口内字符的最大频次(单调不减)
        best = 0
        for r, c in enumerate(s):
            cnt[c] += 1
            if cnt[c] > maxf:
                maxf = cnt[c]
            # 窗口内除最高频字符外,其余都需要替换
            while (r - l + 1) - maxf > k:
                cnt[s[l]] -= 1
                l += 1
            if r - l + 1 > best:
                best = r - l + 1
        return best