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 emtpy string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Hide Tags Hash Table Two Pointers String
Hide Similar Problems (H) Substring with Concatenation of All Words (M) Minimum Size Subarray Sum (H) Sliding Window Maximum
代码
class Solution {
public:
string minWindow(string s, string t) {
if(s.length()<t.length()){
return "";
}
//t中可能存在重复字符串,要统计每个字符的数目
map<char,int> needToFind;
map<char,int> hasFound;
for(int i=0;i<t.length();i++){
if(needToFind.find(t[i])!=needToFind.end()){
needToFind[t[i]]+=1;
}else{
needToFind[t[i]]=1;
hasFound[t[i]]=0;
}
}
char c;
string ret="";
bool retValid=false;
for(int count=0,begin=0,end=0;end<s.size();end++){
c=s[end];
//对s,只处理t中存在的字符,其他的字符直接忽略
if(needToFind.find(c)!=needToFind.end()){
//处理当前字符,更新count和hasFound
if(hasFound[c]<needToFind[c]){
count++;
}
hasFound[c]++;
//begin-end包含全部t的字符
if(count==t.length()){
//先扔掉begin-end中:begin处,不是t中的和hasFound》needTofind
while(needToFind.find(s[begin])==needToFind.end() || hasFound[s[begin]]>needToFind[s[begin]]){
if(needToFind.find(s[begin])!=needToFind.end() && hasFound[s[begin]]>needToFind[s[begin]]){
hasFound[s[begin]]--;
}
begin++;
}
//检查这个子串是否是最短的
if(retValid==false){
retValid=true;
ret=s.substr(begin,end-begin+1);
}else if(end-begin+1 < ret.length()){
ret=s.substr(begin,end-begin+1);
}
}
}
}
return ret;
}
};