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.
终于将这道题以O(n)的复杂度实现了。^_^
class Solution {
public:
string minWindow(string s, string t) {
if(s.empty() || t.empty()){
return "";
}
unordered_map<char, int> mKeys;
int nIndex;
for(nIndex = 0; nIndex < t.length(); nIndex++){
if(mKeys.find(t[nIndex]) != mKeys.end()){
mKeys[t[nIndex]]++;
}else{
mKeys[t[nIndex]] = 1;
}
}
int nLeft = 0, nRight = 0, nMinLeft = 0, nMinRight = 0;
int nCount = 0;
for(nLeft = 0, nRight = 0; nRight < s.length(); nRight++){
if(mKeys.find(s[nRight]) != mKeys.end()){
mKeys[s[nRight]]--;
if(mKeys[s[nRight]] >= 0){
nCount++;
if(nCount == t.length()){
nMinLeft = nLeft;
nMinRight = nRight;
}
}
}
if(nCount == t.length()){
while(mKeys.find(s[nLeft]) == mKeys.end() || mKeys[s[nLeft]] < 0){
if(mKeys.find(s[nLeft]) != mKeys.end()){
mKeys[s[nLeft]]++;
}
nLeft++;
}
if(nRight - nLeft < nMinRight - nMinLeft){
nMinLeft = nLeft;
nMinRight = nRight;
}
}
}
if(nCount < t.length()){
return "";
}else{
return s.substr(nMinLeft, nMinRight-nMinLeft+1);
}
}
};