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.
在S中找到包含T所有字符的最小窗口(类似于文本摘要提取)
用两个指针:start、end
1)若未包含所有字符,则end++;
2)若包含所有字符,则start++,直到不包含为止,得到窗口大小并与当前最小窗口比较并更新。
public class Solution {
public String minWindow(String S, String T) {
int min = S.length()+1;
int minStart = 0;
boolean flag = false;
int count=T.length();
int[] count1 = new int[256];
Map<Character, Boolean> map = new HashMap<Character, Boolean>();
int start=0,end=0;
for(int i=0;i<T.length();i++){
count1[T.charAt(i)]++;
map.put(T.charAt(i), true);
}
for(end=0;end<S.length();end++){
if(map.containsKey(S.charAt(end))&&map.get(S.charAt(end))){
count1[S.charAt(end)]--;
if(count1[S.charAt(end)]>=0){
count--;
}
}
if(count==0){
while(count==0){
if(map.containsKey(S.charAt(start))&&map.get(S.charAt(start))){
count1[S.charAt(start)]++;
if(count1[S.charAt(start)]>0)
count++;
}
start++;
}
if(end-start+2<min){
min=end-start+2;
minStart=start-1;
}
}
}
if(min==S.length()+1)
return "";
return S.substring(minStart,minStart+min);
}
}