標籤:
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 empty string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
思路:問題可以轉變為,T中各個字元的數量<= window中的這些字元的數量,所以用map紀錄字元與字元數量的關係
class Solution {public: bool ifContain(map<char,int>& source, map<char,int>& target) //check if S contains T { for(map<char,int>::iterator it = target.begin(); it != target.end(); it++) //map的遍曆 { if(source[it->first] < it->second) return false; } return true; } string minWindow(string S, string T) { int minLength = INT_MAX; int start = 0, end = 0, minStart = 0, minEnd = 0; map<char,int> source; map<char,int> target; source[S[start]]++; //map的插入[法I]source[key]=value; [法II]source.insert(make_pair(key,value)); for(int i = 0; i< T.length(); i++) { target[T[i]]++; } while(1) { if(ifContain(source, target)){ if(end-start+1 < minLength) { minStart = start; minEnd = end; minLength = end-start+1; if(minLength == T.size()) return S.substr(minStart,minLength); } source[S[start]]--; //尋找更小的視窗 start++; } else //不包含,則擴大視窗 { end++; if(end==S.size()) break; source[S[end]]++; } } if(minLength>S.size()) return ""; else return S.substr(minStart,minLength); }};
76. Minimum Window Substring (Map)