package test;
public class 最小覆盖子串 {
public static String minWindow(String s, String t) {
if (s == null || s == "" || t == null || t == "" || s.length() < t.length()) {
return "";
}
//用来统计t中每个字符出现次数
int[] needs = new int[256];
//用来统计滑动窗口中每个字符出现次数
int[] window = new int[256];
for (int i = 0; i < t.length(); i++) {
needs[t.charAt(i)]++;
}
for (int i = 0; i < t.length(); i++) {
System.out.print(t.charAt(i));
// System.out.print( needs[t.charAt(i)]+" ");
}
System.out.println();
int left = 0;
int right = 0;
//满足条件的字符串
String res = "";
//目前有多少个字符
int count = 0;
//用来记录最短需要多少个字符。
int minLength = s.length() + 1;
//S = "ADOBECODEBANC", T = "ABC"为例
while (right < s.length()) {
//
char ch = s.charAt(right);
window[ch]++;
if (needs[ch] > 0 && needs[ch] >= window[ch]) {
count++;
}
//移动到不满足条件为止
while (count == t.length()) {
ch = s.charAt(left);
if (needs[ch] > 0 && needs[ch] >= window[ch]) {
count--;
}
if (right - left + 1 < minLength) {
minLength = right - left + 1;
//左闭右开
res = s.substring(left, right + 1);
}
//处理完,left向前查找
window[ch]--;
left++;
}
right++;
}
return res;
}
public static void main(String[] args) {
String s= "ADOBECODEBANC";
String t="ABA";
String minWindow = minWindow(s, t);
System.out.println(minWindow);
}
}
12-20
652
11-28
575