题目:
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.
代码:
class Solution { public: string minWindow(string s, string t) { if(s.length() < 1 || t.length() < 1) return ""; map<char, int> dict; int all_rec = 0; for(int i = 0; i<t.length(); i++) { if(dict.find(t[i]) == dict.end()) { dict.insert(pair<char, int>(t[i], 1)); all_rec++; } else dict[t[i]]++; } map<char, int> search; int l = 0, r = 0, rec = 0, res_l = -1, res_r = s.length(); while(l <= r && r < s.length()) { if(search.find(s[r]) == search.end()) search.insert(pair<char, int>(s[r], 1)); else search[s[r]]++; if(dict.find(s[r]) != dict.end() && search[s[r]] == dict[s[r]]) rec++; if(rec == all_rec && res_r - res_l + 1 > r - l + 1) { res_r = r; res_l = l; } while(rec == all_rec && l <= r) { search[s[l]]--; if(dict.find(s[l]) != dict.end() && search[s[l]] < dict[s[l]]) rec--; l++; if(rec == all_rec && res_r - res_l + 1 > r - l + 1) { res_r = r; res_l = l; } } r++; } if(res_l == -1) return ""; return s.substr(res_l, res_r - res_l + 1); } };