问题描述:
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.
题源:here;完整实现:here
思路:
推荐参考文献(here),其简洁性让人信服。同样这道题为了达到快速查找的目的使用了hash
表,代码如下:
string minWindow(string s, string t) {
unordered_map<char, int> hash;
int left = 0, len = INT_MAX, num = t.size(), start = 0;
for (auto val : t) hash[val]++;
for (int i = 0; i < s.size();i++){
if (hash[s[i]]-- > 0) num--;
while (num == 0){
len = len < (i - left + 1) ? len : i - (start = left) + 1;
if (hash[s[left++]]++ == 0) num++;
}
}
return len == INT_MAX ? "" : s.substr(start, len);
}