找到字符串s中的最小窗口,包含字符串t中的所有字符。如果s中不存在符合条件的子串,返回空字符串,否则,存在唯一的最小子串,返回该子串。
使用滑动窗口的方法。首先记录t中的字符串在一个数组中,在s中碰到的时候将值减一,最后逐渐缩小左边界
- 时间复杂度O(s*t)
- 空间复杂度O(1)
- Runtime: 84 ms, faster than 99.29%
- Memory Usage: 41.4 MB, less than 5.84%
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
let max = s.length;
let cur = 0;
let left = 0;
let res = '';
const map = [];
for (let item of t) {
if (!map[item]) {
map[item] = 1;
} else {
map[item]++;
}
}
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (!isNaN(map[ch]) && map[ch]-- > 0) {
cur++;
}
while (t.length === cur) {
if (max >= i - left + 1) {
max = i - left + 1;
res = s.substr(left, max);
}
if (!isNaN(map[s[left]]) && map[s[left]]++ >= 0) {
cur--;
}
left++;
}
}
return res;
};