Minimum Window Substring
76. Minimum Window Substring
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.length
n == t.length
1 <= m, n <= 105
s
andt
consist of uppercase and lowercase English letters.
Follow up: Could you find an algorithm that runs in O(m + n)
time?
分析:
双指针+counter
注意required_char=len(counter_t) not len(t) 需要unique number of char
```python3
from collections import Counter
class Solution:
def minWindow(self, s: str, t: str) -> str:
if len(s) < len(t):
return ""
min_start,min_len,left = 0, float("inf"),0
left = 0
count_window = Counter()
count_t = Counter(t)
formed_char = 0
required_char = len(count_t)
for right, char in enumerate(s):
count_window[char] += 1
if count_window[char] == count_t[char]:
formed_char += 1
while formed_char == required_char:
if min_len > right - left + 1:
min_len = right - left + 1
min_start = left
if count_window[s[left]] == count_t[s[left]]:
formed_char -= 1
count_window[s[left]] -= 1
left += 1
return s[min_start: min_start + min_len] if min_len != float("inf") else ""
```
Last updated
Was this helpful?