题解 | #牛群名字覆盖#

牛群名字覆盖

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
};

全部评论

相关推荐

吴offer选手:学到了,下次面试也放张纸在电脑上,不然老是忘记要说哪几个点
点赞 评论 收藏
分享
喜欢飞来飞去的雪碧在刷代码:可以试一试字节
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务