本文完整拆解 LeetCode 76 Minimum Window Substring 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Minimum Window Substring 一次弄懂。
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
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.lengthn == t.length1 <= m, n <= 105sandtconsist of uppercase and lowercase English letters.
Follow up: Could you find an algorithm that runs in O(m + n) time?
Python
# time complexity: O(len(s) + len(t))
# space complexity: O(len(s) + len(t))
from collections import Counter, defaultdict
class Solution:
def minWindow(self, s: str, t: str) -> str:
reqCount = defaultdict(int)
window = defaultdict(int)
result = [-1, -1]
resultLen = float('inf')
current = 0
for char in t:
reqCount[char] += 1
required = len(reqCount)
left = 0
for right in range(len(s)):
char = s[right]
if char in reqCount:
window[char] += 1
if window[char] == reqCount[char]:
current += 1
while current == required:
if (right - left + 1) < resultLen:
resultLen = right - left + 1
result = [left, right]
leftChar = s[left]
if leftChar in window:
window[leftChar] -= 1
if window[leftChar] < reqCount[leftChar]:
current -= 1
left += 1
return s[result[0]:result[1] + 1] if resultLen != float('inf') else ""
S = "ADOBECODEBANC"
T = "ABC"
print(Solution().minWindow(S, T))
Minimum Window Substring 解題思路
這題是滑動視窗的進階版:視窗要「先擴張到合法,再收縮到最小」。用一張計數表記錄目標字串 t 還缺哪些字元,再用一個 missing 計數器記錄「還差幾個字元才合法」。右指針不斷吃進字元,一旦 missing 歸零就代表視窗合法,接著左指針盡量往右收縮,記錄過程中最短的合法視窗。
Minimum Window Substring 演算法步驟
- 用雜湊表統計 t 中每個字元的需求量,missing 設為 t 的長度。
- 右指針擴張:吃進字元時把需求量減一,若減一前仍大於 0 就 missing–。
- 當 missing 為 0 時視窗合法,嘗試用目前長度更新答案。
- 左指針收縮:把左端字元的需求量加一,若加一後大於 0 代表視窗不再合法,missing++ 並繼續擴張右指針。
Minimum Window Substring 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(m+n) |
| 空間複雜度 | O(k) |
m 是 s 的長度、n 是 t 的長度。左右指針都只單調往右移動,各走訪字串一次,時間為 O(m+n)。雜湊表只存 t 出現過的字元種類 k,空間為 O(k)。
Minimum Window Substring 的邊界情況與常見錯誤
- t 比 s 長或任一為空時直接回傳空字串。
- t 中可能有重複字元,計數表必須記數量而非只記有無。
- 判斷 missing 的加減時機是最容易寫錯的地方,要用「減一前是否大於 0」而非「減一後是否為 0」。
- 答案要回傳子字串,記得保存最佳區間的起點與長度。
Minimum Window Substring 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 列舉所有子字串並檢查 | O(m²·n) | O(k) | 完全不可行 |
| 滑動視窗 + 每次重新驗證 | O(m·k) | O(k) | 正確但重複驗證浪費 |
| 滑動視窗 + missing 計數器 | O(m+n) | O(k) | 本文採用 |
