76. Minimum Window Substring
https://leetcode.com/problems/minimum-window-substring/
solution
class Solution:
def minWindow(self, s: str, t: str) -> str:
t_counter = collections.Counter(t)
s_counter = collections.defaultdict(int)
l = 0
valid_length = 0 # 记录窗口内和target对比的有效长度
res = float('inf')
res_start = -1
for r, char in enumerate(s):
s_counter[char] += 1
if s_counter[char] <= t_counter[char]:
valid_length += 1
while valid_length == len(t):
if r - l + 1 < res:
res = r - l + 1
res_start = l
if s_counter[s[l]] <= t_counter[s[l]]:
valid_length -= 1
s_counter[s[l]] -= 1
l += 1
return "" if res_start < 0 else s[res_start: res_start + res]时间复杂度:O(m+n) 空间复杂度:O(c)
follow up
统一思路:用哈希/数值计数器记录"still need",双指针/滑动窗口用O(n)复杂度求解子串问题
3. Longest Substring Without Repeating Characters
30. Substring with Concatenation of All Words
438. Find All Anagrams in a String
*340. Longest Substring with At Most K Distinct Characters
992. Subarrays with K Different Integers
*159. Longest Substring with At Most Two Distinct Characters
Previous424. Longest Repeating Character ReplacementNext3. Longest Substring Without Repeating Characters
Last updated