1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution: def minWindow(self, word1: str, word2: str) -> str: ans = 0 b_cnt = defaultdict(int) for s in word2: b_cnt[s] += 1 n = len(word1) a_cnt = defaultdict(int) tmp = 0 st = 0
for i in range(0, n): if tmp == len(word2): break st = i a_cnt[word1[i]] += 1
if a_cnt[word1[i]] == b_cnt[word1[i]]: tmp += b_cnt[word1[i]] if tmp != len(word2): return "" ans = 0
tt = 0 while a_cnt[word1[tt]] - 1 >= b_cnt[word1[tt]]: a_cnt[word1[tt]] -= 1 tt += 1 l = tt r = st mi = st - tt
for i in range(st+1, n):
a_cnt[word1[i]] += 1 while a_cnt[word1[tt]] - 1 >= b_cnt[word1[tt]]: a_cnt[word1[tt]] -= 1 tt += 1 if i - tt < mi: mi = i - tt l = tt r = i return word1[l:r+1]
|