题目:
题目截图:
解题步骤:
1.用双指针维护一个滑动窗口
2.移动右指针,找到包含t的子串,移动左指针,尽量减少包含t的子串的长度
3.循环上述过程,找出包含t的最小子串
代码:
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function (s, t) {
let l = r = 0;
const need = new Map();
// 字典中存储的是需要的字符及对应的个数
for (let c of t) {
need.set(c, need.has(c) ? need.get(c) + 1 : 1);
}
// 存储需要字符的类型个数,就像"ABC","A":1,"B":1,"C":1
let needType = need.size;
let res = '';
// console.log(need)
while (r < s.length) {
const c = s[r];
if (need.has(c)) {
need.set(c, need.get(c) - 1);
if (need.get(c) === 0) needType -= 1; // 某个需要字符的个数为0了,就将需要字符类型的个数减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; // 不断更新res
const c2 = s[l];
if (need.has(c2)) {
need.set(c2, need.get(c2) + 1); // 重新记录一下需要的字符
if (need.get(c2) === 1) needType += 1; // 有一个的时候,将类型加1
}
l += 1;
}
r += 1;
}
return res;
};
时间复杂度分析:
时间复杂度:O(m + n),m是t的长度,n是s的长度
空间复杂度分析:
空间复杂度:O(k),k是t中不同字符的长度
怎么样,是不是很简单,你学会了吗 ?
如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续努力的动力 💪💪!!!