您的位置:首页 > 其它

leetcode-Minimum Window Substring

2015-11-03 21:09 429 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: