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.
滑动子窗口(为了让代码精简,用int[128],不要用HashMap):
public class Solution {
public String minWindow(String s, String t) {
int[] map=new int[128];
int[] map2=new int[128];
for(int i=0;i<t.length();i++) map[t.charAt(i)]++;
int n=0;
int reStart=0,reEnd=Integer.MAX_VALUE;
int start=0;
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(map[ch]>0){
if(map2[ch]<map[ch]) n++;
map2[ch]++;
}
if(n>=t.length()){
int k=start;
for(;k<=i;k++){
char c=s.charAt(k);
if(map[c]==0) continue;
if(map2[c]>map[c]){
map2[c]--;
}else break;
}
start=k;
if(reEnd-reStart>i-start){
reEnd=i;
reStart=start;
}
}
}
if(reEnd==Integer.MAX_VALUE) return "";
else return s.substring(reStart,reEnd+1);
}
}