/**
* 解题思路
* - 包含所有的包含 T 的子串
* - 找出长度最小的那个字串,返回即可。
*
* 解题步骤
* - 用双指针维护一个滑动窗口。
* - 移动右指针,找到包含 T 的子串,移动左指针,尽量减少包含 T 的子串的长度.
*/
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
let l = 0,
r = 0;
const map = new Map();
for (let c of t) {
map.set(c, map.has(c) ? map.get(c) + 1 : 1);
}
let needType = map.size;
// 记录最小的子串
let res = '';
while (r < s.length) {
const c = s[r];
if (map.has(c)) {
map.set(c, map.get(c) - 1);
// 怎么知道已经满足了需求。
if (map.get(c) === 0) {
needType -= 1;
}
}
while(needType === 0) {
// 包含了所有的子串。
// console.log(s.substring(l, r + 1));
const newRes = s.substring(l, r + 1);
if (!res || newRes.length < res.length) res = newRes;
const c2 = s[l];
if (map.has(c2)) {
map.set(c2, map.get(c2) + 1);
if (map.get(c2) === 1) needType += 1;
}
l += 1;
}
r++;
}
return res;
};
最小覆盖子串
最新推荐文章于 2024-07-26 11:41:15 发布