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).
Example:
Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC"
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
考察:string,hash,map;
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> m;
for (int i = 0; i < t.length(); i ++)
m[t[i]] ++;
int left = 0, minLen = s.length(), count = 0;
string res = "";
for (int i = 0; i < s.length(); i ++) {
m[s[i]] --;
if (m[s[i]] >= 0)
count ++;
while(count == t.length()) {
if (minLen >= i - left + 1) {
minLen = i - left + 1;
res = s.substr(left, minLen);
}
if (m[s[left]] >= 0) // left是否在t中
count --;
m[s[left]] ++; // left移除窗口
left ++;
}
}
return res;
}
};