题解 | #牛群名字覆盖#
牛群名字覆盖
https://www.nowcoder.com/practice/e6cef4702e7841f59cf47daf9bafb241
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param t string字符串
* @return string字符串
*/
function minWindow(s, t) {
// write code here
let target = getCharCount(t)
let totalChar = Object.values(target).reduce((a, b) => a + b) - 1
let left = 0
let res = ""
while (left <= s.length - totalChar) {
let right = left + totalChar - 1
while (right <= s.length) {
let str = s.slice(left, right)
let strObj = getCharCount(str)
if (isEaualObject(target, strObj)) {
if (res === "") {
res = str
} else {
res = str.length < res.length ? str : res
}
}
right++
}
left++
}
return res
}
function isEaualObject(obj1, obj2) {
for (const k of Object.keys(obj1)) {
if (obj1[k] !== obj2[k]) {
return false
}
}
return true
}
function getCharCount(s) {
let obj = {}
for (const c of s) {
if (obj.hasOwnProperty(c)) {
obj[c]++
} else {
obj[c] = 1
}
}
return obj
}
module.exports = {
minWindow: minWindow
};
