题目描述
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.
A substring is a contiguous sequence of characters within the string.
解题思路
看到时间复杂度的要求,第一时间想到的是能不能用空间换时间。常用的方法就是字典,一遍遍历过去,我们想尽快的知道我们目前的一个解(有可能是次优解),与目标串 t 的关系究竟如何,也就是说,当前的解是不是存在冗余?如果存在我们应该将其“瘦身”,然后保存得到的每一个解,最后求最小就可了。
代码
class Solution:
def minWindow(self, s: str, t: str) -> str:
hash_table = {}
cnt = 0
minLen = 1000000
ans = ""
left = 0
for i in t:
if i in hash_table.keys():
hash_table[i] += 1
else:
hash_table[i] = 1
for i in range(len(s)): # i 相当于 tail,left 为 head
if s[i] in hash_table.keys() and hash_table[s[i]] > 0:
cnt += 1
hash_table[s[i]] -= 1
elif s[i] in hash_table.keys():
hash_table[s[i]] -= 1
while cnt == len(t): # 当前得到的解是不是存在冗余
if i - left < minLen:
minLen = i - left + 1
ans = s[left:i + 1]
if s[left] in hash_table.keys() and hash_table[s[left]] < 0:
hash_table[s[left]] += 1
left += 1
elif s[left] not in hash_table.keys():
left += 1
else:
hash_table[s[left]] += 1
left += 1
cnt -= 1
return ans