标签:mini 一个 res nat ini ++ data 实现 which
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 emtpy string"".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
找出包含T所有字母的最小窗口。
注意:S=bba t=ba。此时right=2时,left=0,移动left时会++m[b],但是此时窗口内仍旧有一个b。所以在right移动时,m[b]=-1,即只要包含即--,而只有m[b]>=0时,才是有效的,才会++count。同样,在移动left时也是,只有m[b]>0时,才会count--。
1 class Solution { 2 public: 3 string minWindow(string S, string T) { 4 if(S.length()==0) 5 return ""; 6 map<char, int> m; 7 for(int i=0;i<T.length();i++){ 8 if(m.find(T[i])!=m.end()) 9 m[T[i]]++; 10 else 11 m[T[i]]=1; 12 } 13 int left=0,right=0,min=S.length()+1,minStart=0,count=0; 14 for(right=0;right<S.length();right++){ 15 if(m.find(S[right])==m.end()) 16 continue; 17 m[S[right]]--; 18 if(m[S[right]]>=0){ 19 count++; 20 } 21 while(count==T.length()){ 22 if((right-left+1)<min){ 23 min=right-left+1; 24 minStart=left; 25 } 26 if(m.find(S[left])!=m.end()){ 27 m[S[left]]++; 28 if(m[S[left]]>0) 29 count--; 30 } 31 left++; 32 } 33 } 34 string res=""; 35 if(min!=S.length()+1){ 36 res=S.substr(minStart,min); 37 } 38 return res; 39 } 40 };
LeetCode-Minimum Window Substring -- 窗口问题
标签:mini 一个 res nat ini ++ data 实现 which
原文地址:http://www.cnblogs.com/zl1991/p/7092139.html