最小覆盖子串
题目描述
代码
import java.util.*;
public class Solution {
/**
*
* @param S string字符串
* @param T string字符串
* @return string字符串
*/
public String minWindow (String S, String T) {
// write code here
//记录T中所有字符出现的次数
int[] map = new int[128];
for(int i=0; i<T.length(); i++){
map[T.charAt(i)]++;
}
//左右指针,end先查询包含全部T字符,begin进行缩减子字符串
int begin=0, end=0;
int count = T.length();
//记录最小子字符串的头
int head = 0;
//窗口大小
int window = Integer.MAX_VALUE;
while(end < S.length()){
//每个出现的字符的次数都要减1,命中存在的字符,则比较的次数-1
if( map[S.charAt(end)]-- > 0){
count--;
}
end++;
//全部命中,begin移动
while(count == 0){
//寻找最小窗口
if(end - begin < window){
head = begin;
window = end - begin;
}
//若begin指向的字符刚好被命中完的状态,则count+1
//同时,移除的字符需要回加1
if( map[S.charAt(begin)]++ == 0 ){
count++;
}
begin++;
}
}
return window==Integer.MAX_VALUE ? "" :S.substring(head,head+window);
}
}