题目描述:
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.
解题思路:
- 这道题是一道典型的滑动窗口问题
- 我的解法是参考网上其他大佬的,所以具体看代码
代码如下:
public String minWindow(String S, String T) {
int [] map = new int[128];
// 记录 T 中每个元素的个数
for(int i = 0; i < T.length(); i++){
map[T.charAt(i)]++;
}
// begin,end 两个指针指向窗口的首位, d 记录窗口的长度, count 记录 T 中还有几个字符没有被窗口包含
int begin = 0,end = 0, d = Integer.MAX_VALUE, count = T.length(), head = 0;
while(end < S.length()){
// map[] > 0 表示该字符在 T 中出现
if(map[S.charAt(end++)]-- > 0){
count--;
}
// 当 count == 0 时,说明该窗口已经包含了 T 中所有的字符
// 记录当前窗口
while(count == 0){
if(end -begin < d){
d = end - (head = begin);
}
// 此时 begin 继续寻找其他可能的窗口
if(map[S.charAt(begin++)]++ == 0 ){
count++;
}
}
}
return d == Integer.MAX_VALUE ? "" : S.substring(head,head + d);
}