File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ *** 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。***
2+
3+ ```
4+ 输入:s = "ADOBECODEBANC", t = "ABC"
5+ 输出:"BANC"
6+ ```
7+
8+ ```
9+ #我们可以用滑动窗口的思想解决这个问题。在滑动窗口类型的问题中都会有两个指针,一个用于「延伸」现有窗口的 r 指针,和一个用于「收缩」窗口的 l 指针。在任意时刻,只有一个指针运动,而另一个保持静止。
10+ #我们在 s 上滑动窗口,通过移动 r 指针不断扩张窗口。当窗口包含 t 全部所需的字符后,如果能收缩,我们就收缩窗口直到得到最小窗口。
11+
12+ class Solution:
13+ def minWindow(self, s: str, t: str) -> str:
14+ left = 0
15+ min_len = float('inf')
16+ res = ''
17+ #用一个哈希表动态维护窗口中所有的字符以及它们的个数
18+ target = {}
19+ cnt = 0
20+ for c in t:
21+ if c not in target:
22+ target[c] = 1
23+ cnt += 1
24+ else:
25+ target[c] += 1
26+
27+ for ind, c in enumerate(s):
28+ if c in target:
29+ target[c] -= 1
30+ if target[c] == 0:
31+ cnt -= 1
32+ while not cnt:
33+ cur_len = ind-left+1
34+ if cur_len < min_len:
35+ min_len = cur_len
36+ res = s[left:ind+1]
37+ if s[left] in target:
38+ target[s[left]] += 1
39+ if target[s[left]] > 0:
40+ cnt += 1
41+ left += 1
42+ return res
43+ ```
You can’t perform that action at this time.
0 commit comments