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 =
T =
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.
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.
[Thoughts]:
滑动窗口,头指针从头开始,尾指针往后滑动,直到包含T中所有字母。 如果头指针所指元素不是T中的或多余的,调整头指针。
public class Solution {
public String minWindow(String S, String T) {
HashMap<Character, Integer> smap = new HashMap<Character, Integer>();
HashMap<Character, Integer> tmap = new HashMap<Character, Integer>();
//初始化smap和tmap, tmap是T中所有char的map, smap使我们需要用S去更新的map。
for(int i=0; i<T.length(); i++){
if(!tmap.containsKey(T.charAt(i))){
tmap.put(T.charAt(i), 1);
smap.put(T.charAt(i), 0);
}else
tmap.put(T.charAt(i), tmap.get(T.charAt(i))+1);
}
//minstart和 minend是目的头指针和尾指针
int minstart = -1;
int minend = S.length();
int count = 0;//count跟踪T里面的字母, 当count==T.length时,smap里已包含所有T的字母。
for(int start=0, end=0; end<S.length(); end++){
char c = S.charAt(end);
if(!smap.containsKey(c))
continue;
smap.put(c, smap.get(c)+1);
if(smap.get(c)<=tmap.get(c))//count++,说明我们考虑c是T里面的一个字母
count++;
if(count == T.length()){//已经找到一个窗口
//while循环调整头指针以缩小窗口, 若头指针指的元素我们不需要,那么头指针前进。
while(!smap.containsKey(S.charAt(start)) || smap.get(S.charAt(start)) > tmap.get(S.charAt(start))){
if(smap.containsKey(S.charAt(start)))
smap.put(S.charAt(start), smap.get(S.charAt(start))-1);
start++;
}
//更新窗口
if(minend-minstart > end-start){
minstart = start;
minend = end;
}
}
}
//若没有找到窗口,返回空串
return minstart==-1 ? "" : S.substring(minstart, minend+1);
}
}
No comments:
Post a Comment