150強訪談簡單

最小視窗子字串

“最小視窗子串”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定長度分別為 mn 的兩個字串 st,傳回 s 的最小視窗子字串,使得 t 中的每個字元(包括重複字元)都包含在視窗中。如果不存在這樣的子字串,則傳回空字串 ""

答案保證是唯一的。

寫一個函數 minWindow(s: str, t: str) -> str

約束條件
  • m == len(s), n == len(t)
  • 1 <= m, n <= 10^5
  • s and t consist of uppercase and lowercase English letters

範例

Example 1
Input
s = "ADOBECODEBANC", t = "ABC"
Output
"BANC"
Explanation

The minimum window substring "BANC" (indices 9-12) contains 'A', 'B', and 'C' from 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. Since s only has one 'a', return empty string.

Need a Hint?
考慮使用滑動視窗特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。