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.
Solution:Code:
<span style="font-size:14px;">class Solution {
public:
string minWindow(string S, string T) {
int lengthS = S.size(), lengthT = T.size();
if (lengthT > lengthS) return "";
unordered_map<char, int> hashTable;
for (int i = 0; i < lengthT; i++)
hashTable[T[i]]++;
int count = 0, begin = 0, end = 0;
for (; end < lengthS; end++)
if (hashTable.find(S[end]) != hashTable.end()) {
hashTable[S[end]]--;
if (hashTable[S[end]] >= 0) count++;
if (count == lengthT) break;
}
if (count != lengthT) return "";
for (; begin <= end; begin++)
if (hashTable.find(S[begin]) == hashTable.end()) continue;
else if (hashTable[S[begin]] < 0) hashTable[S[begin]]++;
else if (hashTable[S[begin]] == 0) break;
int minLength = end-begin+1;
int result = begin;
end++;
for (; end < lengthS; end++)
if (S[begin] == S[end]) {
begin++;
for (; begin <= end; begin++)
if (hashTable.find(S[begin]) == hashTable.end()) continue;
else if (hashTable[S[begin]] < 0) hashTable[S[begin]]++;
else if (hashTable[S[begin]] == 0) break;
if (end-begin+1 < minLength) {
minLength = end-begin+1;
result = begin;
}
} else {
if (hashTable.find(S[end]) != hashTable.end())
hashTable[S[end]]--;
}
return S.substr(result, minLength);
}
};</span>