题解 | #最小覆盖子串#
最小覆盖子串
https://www.nowcoder.com/practice/c466d480d20c4c7c9d322d12ca7955ac
/**
*
* @param S string字符串
* @param T string字符串
* @return string字符串
*/
function minWindow( s , t ) {
// write code here
const needMap = new Map()
for (const char of t) {
needMap.set(char, needMap.get(char) + 1 || 1)
}
const targetLength = needMap.size
const matchMap = new Map()
let match = 0
let res = ''
let i = 0
let j = 0
while (j < s.length) {
let char = s[j]
if (needMap.has(char)) {
matchMap.set(char, matchMap.get(char) + 1 || 1)
if (needMap.get(char) === matchMap.get(char)) {
match++
}
}
while (match === targetLength) {
if (!res || res.length > (j - i + 1)) {
res = s.slice(i, j + 1)
}
i++
const lastChar = s[i - 1]
if (matchMap.has(lastChar)) {
matchMap.set(lastChar, matchMap.get(lastChar) - 1)
if (matchMap.get(lastChar) < needMap.get(lastChar)) {
match--
}
}
}
j++
}
return res
}
module.exports = {
minWindow : minWindow
};
上海得物信息集团有限公司公司福利 1166人发布
查看16道真题和解析