核心思想
滑动窗口,先从头开始找到包含t的子串,然后缩短窗口左边界,直到不包含再扩展右边界。
匹配过程:
s = "ADOBECODEBANC", t = "ABC"
匹配:"ADOBEC"
缩短:"DOBEC"
匹配:"DOBECODEBA"
缩短:"ODEBA"
匹配:"ODEBANC"
缩短:"ANC"
缩短过程中记录答案
代码
public String minWindow(String s, String t) {
int res = s.length() + 1, resL = -1, resR = -1;
HashMap<Character, Integer> vs = new HashMap();
HashMap<Character, Integer> vt = new HashMap();
for(int i = 0; i < t.length(); i++){
vt.put(t.charAt(i), vt.getOrDefault(t.charAt(i), 0) + 1);
}
int cnt = 0, target = t.length();
for(int l = 0, r = 0; r < s.length(); r++){
vs.put(s.charAt(r), vs.getOrDefault(s.charAt(r), 0) + 1);
if(vs.get(s.charAt(r)) <= vt.getOrDefault(s.charAt(r), 0)){
cnt++;
}
if(cnt == target){
while(true){
if(r - l + 1 < res){
res = Math.min(res, r - l + 1);
resL = l;
resR = r;
}
char ch = s.charAt(l);
vs.put(ch, vs.get(ch) - 1);
l++;
if(vs.get(ch) < vt.getOrDefault(ch, 0)){
cnt--;
break;
}
}
}
}
return resL == -1? "": s.substring(resL, resR + 1);
}
}
标签:子串,HashMap,int,最小,76,length,vs,缩短,charAt
From: https://www.cnblogs.com/ganyq/p/18109079