# day11-最小覆盖子串-滑动窗口
给你一个字符串 s
、一个字符串 t
。返回 s
中涵盖 t
所有字符的最小子串。如果 s
中不存在涵盖 t
所有字符的子串,则返回空字符串 ""
。
注意:
- 对于
t
中重复字符,我们寻找的子字符串中该字符数量必须不少于t
中该字符数量。 - 如果
s
中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"
解释:最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。
1
2
3
2
3
示例 2:
输入:s = "a", t = "a"
输出:"a"
解释:整个字符串 s 是最小覆盖子串。
1
2
3
2
3
示例 3:
输入: s = "a", t = "aa"
输出: ""
解释: t 中两个字符 'a' 均应包含在 s 的子串中,
因此没有符合条件的子字符串,返回空字符串。
1
2
3
4
2
3
4
提示:
m == s.length
n == t.length
1 <= m, n <= 105
s
和t
由英文字母组成
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
let tempObj = {};
for(const ch of t){
tempObj[ch] = tempObj[ch] ? tempObj[ch] + 1 : 1;
}
let left = right = 0;
let count = Object.keys(tempObj).length;
let minStr = "";
let minLen = Infinity;
// 指针右移
while(right < s.length){
const charRight = s[right];
if(charRight in tempObj){
tempObj[charRight]--;
if(tempObj[charRight] === 0){
count--;
}
}
right++;
while(count === 0){
if(right - left < minLen){
// 更新最小值信息
minLen = right - left;
minStr = s.slice(left,right);
}
const charLeft = s[left];
if(charLeft in tempObj){
tempObj[charLeft]++;
if(tempObj[charLeft] > 0){
count++;
}
}
left++;
}
}
return minStr;
};
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
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