Longest Repeating Character Replacement 解題教學:3 種解法完整比較|LeetCode 424 Best Practice

Longest Repeating Character Replacement 解題教學示意圖|LeetCode 424

本文完整拆解 LeetCode 424 Longest Repeating Character Replacement 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Longest Repeating Character Replacement 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

 

Example 1:

Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.

Example 2:

Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
There may exists other ways to achieve this answer too.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only uppercase English letters.
  • 0 <= k <= s.length

Python

				
					# time complexity: O(n)
# space complexity: O(1)
from collections import defaultdict


class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        result = 0
        left = right = 0
        freq = defaultdict(int)
        mostFreqChar = 0
        for right in range(len(s)):
            freq[s[right]] += 1

            mostFreqChar = max(mostFreqChar, freq[s[right]])

            if right - left + 1 - mostFreqChar > k:
                freq[s[left]] -= 1
                left += 1
            
            result = max(result, right - left + 1)

        return result


s = "AABABBA"
k = 1
print(Solution().characterReplacement(s, k))
				
			

Longest Repeating Character Replacement 解題思路

視窗合法的條件是「視窗長度減去視窗內出現最多的字元數」不超過 k,也就是要替換的字元數在預算內。巧妙之處在於:maxCount 不需要在視窗收縮時回頭重算,因為答案只關心歷史最大值,maxCount 偏大只會讓視窗不再成長,不會算出錯誤答案。

Longest Repeating Character Replacement 演算法步驟

  1. 用 26 格計數陣列記錄視窗內各字元數量,left = 0、maxCount = 0。
  2. 右指針擴張,把 s[right] 的計數加一並更新 maxCount。
  3. 若 (right – left + 1) – maxCount 大於 k,代表要替換的太多,把 s[left] 計數減一並 left++。
  4. 每一輪用目前視窗長度更新答案的最大值。

Longest Repeating Character Replacement 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(1)

左右指針都只單調往右,各走訪一次,時間為 O(n)。計數陣列固定 26 格,空間為 O(1)。這是滑動視窗中少見的「不回頭重算」技巧。

Longest Repeating Character Replacement 的邊界情況與常見錯誤

  • k 等於 0 時退化成求最長連續相同字元。
  • 視窗每次只收縮一格即可,因為右指針一次只擴張一格。
  • maxCount 不需要在收縮時減少,這點違反直覺但可以證明不影響答案。
  • 字串只含大寫英文字母時才能用 26 格陣列,否則改用雜湊表。

Longest Repeating Character Replacement 其他解法比較

解法時間空間說明
列舉所有子字串並檢查O(n²)O(1)完全不可行
對 26 個字元各跑一次滑動視窗O(26n)O(1)思路更直觀,常數較大
單次滑動視窗 + maxCountO(n)O(1)本文採用