Problem: 76. 最小覆盖子串
窗口左右边界为i和j,初始值都为0,j一直往右搜索,然后记录一下窗口内的字符是否达到了全部覆盖,如果达到了,那么就开始i往右搜索,找最短的子串,直到不满足全部覆盖了,那么再继续搜j
时间复杂度:
添加时间复杂度, 示例: O ( n ) O(n) O(n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = collections.defaultdict(int)
for ch in t:
need[ch] += 1
count = len(t)
i = 0
res = (0, math.inf)
for j, ch in enumerate(s):
if need[ch] > 0:
count -= 1
need[ch] -= 1
if count == 0: # 包含了所以元素了
while True:
c = s[i]
if need[c] == 0:
break
need[c] += 1
i += 1
if j - i < res[1] - res[0]:
res = (i, j)
need[s[i]] += 1
i += 1
count += 1
if res[1] == math.inf:
return ""
else:
return s[res[0]: res[1] + 1]