leetcode-Minimum Window Substring

来源:互联网 发布:smart电子白板软件 编辑:程序博客网 时间:2024/06/05 09:20

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).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the empty string"".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.


class Solution {public:    string minWindow(string s, string t) {        int slen=s.length();        int tlen=t.length();        if(tlen<=0||tlen>slen)            return string("");        map<char,int> S;        map<char,int> T;        for(auto &e:t)            ++T[e];        string res;            int end=0,begin=0,minlen=INT_MAX;        int count=0;        for(;end<slen;++end){            if(T.find(s[end])==T.end())                continue;            ++S[s[end]];            if(S[s[end]]<=T[s[end]])                ++count;            if(tlen==count){                while(T.find(s[begin])==T.end()||S[s[begin]]>T[s[begin]]){                    if(T.find(s[begin])!=T.end())                        --S[s[begin]];                    ++begin;                    }                if(end-begin+1<minlen){                    minlen=end-begin+1;                    res=s.substr(begin,minlen);                }            }            }        return res;    }};


0 0