s
和t
由英文字母组成
class Solution {
public String minWindow(String s, String t) {
//窗口包含字符:左移、不包含:右移
String res = "";
int ns = s.length();
int nt= t.length();
int length=ns;
if(ns<nt) return "";
//寻找满足条件的可行窗口
int[] count = new int[60];
//记录初始窗口与目标字符串相差哪几个字母
//如果count[i]大于0 则说明在t中有 在当前窗口没有
//如果count[i] == 0 则说明t和当前窗口都有
//如果count[i]小于0 则说明在t中没有 在当前窗口有 ->不需要关注
for (int i = 0; i < nt; i++) {
count[t.charAt(i) - 'A'] ++;
count[s.charAt(i) - 'A'] --;
}
if (isContains(count)) return s.substring(0, t.length());
//窗口一直满足,缩短
for (int i = t.length(),left=0; i < s.length(); ++ i){
count[s.charAt(i) - 'A'] -- ;//右移
while (areAllZero(count)){
if (length >= i - left + 1) {
//更新
length = i - left + 1;
res = s.substring(left,i+1);
}
count[s.charAt(left)-'A']++;//左侧
left++;
}
}
return res;
}
private boolean isContains(int[] count) {
for (int i : count) {
if(i>0){
return false;
}
}
return true;
}
}