class Solution {
public String minWindow(String s, String t) {
//System.out.println("111");
//字符串s的长度
int slen = s.length();
//字符串t的长度
int tlen = t.length();
//记录滑动窗口中t中字符出现的情况
Map<Character,Integer> winmap = new HashMap<>();
//记录t中字符情况
Map<Character,Integer> tmap = new HashMap<>();
//计算t中字符出现个数
for(int i = 0; i < tlen;i++){
tmap.put(t.charAt(i),tmap.getOrDefault(t.charAt(i),0) + 1);
}
int left = 0;
int right = 0;
int total = 0;
int min = Integer.MAX_VALUE;
String ans = "";
for(right = 0; right < slen; right++){
char ch = s.charAt(right);
if(tmap.getOrDefault(ch,0) != 0){
winmap.put(ch,winmap.getOrDefault(ch,0)+1);
if(winmap.getOrDefault(ch,0).equals(tmap.getOrDefault(ch,0)))
total += 1;
//错误 Integer 是对象!! !
// if(winmap.getOrDefault(ch,0) == tmap.getOrDefault(ch,0))
// total += 1;
}
while(total == tmap.size()){ //窗口中已经包括了t中的所有字符
if(right - left + 1 < min)
{
min = right - left + 1;
ans = s.substring(left,right+1);
}
char lch = s.charAt(left);
left += 1;
if(tmap.getOrDefault(lch,0) != 0){
if(winmap.getOrDefault(lch,0).equals(tmap.getOrDefault(lch,0)))
total -= 1;
winmap.put(lch,winmap.getOrDefault(lch,0) - 1);
}
}
}
return ans;
}
}
注意: 用 == 最后一个测试用例通不过 Map的value是Integer是一个对象 == 是对对象引用的比较 equals是对对象值的比较
221108
class Solution {
public String minWindow(String s, String t) {
Map<Character,Integer> tmap = new HashMap<>();
for(int i = 0; i < t.length();i++){
tmap.put(t.charAt(i),tmap.getOrDefault(t.charAt(i),0) + 1);
}
Map<Character,Integer> windows = new HashMap<>();
int left = 0;
int right = 0;
int vaild = 0;
int ans = Integer.MAX_VALUE;
String ansStr = "";
while(right < s.length()){
char cur = s.charAt(right);
if(tmap.containsKey(cur)){
windows.put(cur,windows.getOrDefault(cur,0) + 1);
if(windows.get(cur).equals(tmap.get(cur)))
vaild += 1;
}
//收缩滑动窗口 直到滑动窗口不满足条件
while(tmap.size() == vaild){
if(right-left + 1 < ans){
ans = right-left + 1;
ansStr = s.substring(left,right+1);
}
char lc = s.charAt(left);
left += 1;
if(tmap.containsKey(lc)){
if(windows.get(lc).equals(tmap.get(lc)))
vaild -= 1;
windows.put(lc,windows.getOrDefault(lc,0) - 1);
}
//继续向后移动right 直到滑动窗口满足条件
}
right += 1;
}
return ansStr;
}
}