76. Minimum Window Substring(js)

76. Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
题意:找出S中长度最小的子串,满足T中所有字符都在子串中
代码如下:
/**
 * @param {string} s
 * @param {string} t
 * @return {string}
 */
var minWindow = function(s, t) {
    let res="";
    let obj={};
    let left=0,cnt=0,minLen=Infinity;
//     统计t中的所有字符
    for(let i=0;i<t.length;i++) {
        if(obj.hasOwnProperty(t[i])){
            obj[t[i]]++;
        }else{
            obj[t[i]]=1;
        }
    }
//     
    for(let i=0;i<s.length;i++){
        if(--obj[s[i]]>=0) ++cnt;
        while(cnt===t.length){
            if(minLen>i-left+1){
                minLen=i-left+1;
                res=s.substr(left,minLen);
            }
            if(++obj[s[left]]>0) --cnt;
            ++left;
        }
    }
    return res;
};

 




posted @ 2019-03-20 21:49  mingL  阅读(160)  评论(0编辑  收藏  举报