思路
暴力解法:对每个元素都分别遍历,以它为开头,可以满足的子串长度。然后求解
优化:设i,j两个下标,且i< j。如果我们已经找到了以i为开头的子串,且i和j之间的元素不影响子串,那么我们就可以直接跳过之间的元素,减少重复。
Python版本
class Solution:
def minWindow(self, s: str, t: str) -> str:
if len(t) > len(s):
return ''
n = len(s)
smap = dict()
tmap = dict()
def check(smap,tmap):
for key,value in tmap.items():
if tmap[key] > smap[key]:
return False
return True
# 构造tmap
for c in t:
if c not in tmap:
tmap[c] = 1
else:
tmap[c] += 1
smap[c] = 0
left = 0
right = 0
res = ""
while right < n:
while not check(smap,tmap) and right < n:
if s[right] in smap:
smap[s[right]] += 1
right += 1
while check(smap,tmap) and left < right:
ans = s[left:right]
if not res or len(ans) < len(res):
res = ans
if s[left] in smap:
smap[s[left]] -= 1
left += 1
return res