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 =
T =
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 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.
class Solution { public: string minWindow(string s, string t) { if(t.empty()) return ""; vector<int> set(128,0), found(128,0); for(int i=0;i<t.length();i++) set[t[i]]++; queue<int> indexQueue; int minLen = INT_MAX, minStart=0, minEnd=0; int start = 0, end = start, ocurrence = 0; while(true){ if(ocurrence < t.length()) { while(end<s.length() && !set[s[end]]) end++; if(end == s.length()) break; char c = s[end]; indexQueue.push(end); found[c] ++; if(found[c] <= set[c]) ocurrence ++; end ++; } while(ocurrence == t.length()){ start = indexQueue.front(); indexQueue.pop(); if(found[s[start]]==set[s[start]]) ocurrence --; found[s[start]] --; int cur = end - start; if(cur < minLen) { minLen = cur; minStart = start; minEnd = end; } } } return s.substr(minStart, minEnd-minStart); } };