
java
class Solution {
public String minWindow(String s, String t) {
if(s == null || s.length() == 0 || t == null || t.length() == 0){
return "";
}
//存放t字符串中的字符个数
int[] need = new int[128];
//将t字符串存放进need数组中
for(int i = 0; i < t.length(); i++){
need[t.charAt(i)]++;
}
//左右指针
int left = 0, right = 0;
//记录t字符串的总长度
int needCount = t.length();
//记录最短字串的起始位置
int minStart = 0;
//记录最短字串的长度,先初始化
int minLen = Integer.MAX_VALUE;
while(right < s.length()){
char c = s.charAt(right);
//这个字符是所需要的就将字符串总长度-1
if(need[c] > 0){
needCount--;
}
need[c]--;
if(needCount == 0){
//清空后使用left指针进行多余字符的处理
while(left < right && need[s.charAt(left)] < 0){
//将处理后的字符+1
need[s.charAt(left)]++;
left++;
}
//记录当前的最短窗口
if(right - left + 1 < minLen){
minLen = right - left + 1;
minStart = left;
}
//将left当前所处的最前面的字符去掉,往后寻找是否存在更短字串
need[s.charAt(left)]++;
needCount++;
left++;
}
right++;
}
//返回空串或者截取最短字串
return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart,minStart + minLen);
}
}
1.将字串t存放到数组中
2.使用right指针处理need数组和needCount计数器
3.得到第一个最小字串
4.处理字串中前方多余的字符
5.单个字母依次踢出最小字串中,往后寻找更优的字串
while (left < right && need[s.charAt(left)] < 0):存在need[s.charAt(left)] < 0这个条件left本身不会超过right,但是为了安全,加了left < right这层保障