滑動窗口,check()
判斷當前是否滿足覆蓋條件,滿足head
後移,不滿足tail
後移import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
class Solution {
private Map<Character, Integer> m = new HashMap<Character, Integer>();
private Map<Character, Integer> tmpcount = new HashMap<Character, Integer>();
private boolean check() {
Iterator it = m.entrySet().iterator();
char key;
int value;
while (it.hasNext()) {
Map.Entry mt = (Map.Entry) it.next();
key = (char) mt.getKey();
value = (int) mt.getValue();
if (tmpcount.getOrDefault(key, 0) < value) return false;
}
return true;
}
public String minWindow(String s, String t) {
String res = "";
for (int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
m.put(c, m.getOrDefault(c, 0) + 1);
}
int head = 0;
int tail = 0;
while (tail < s.length() || check()) {
if (check()) {
if (res.length() == 0 || res.length() > (tail - head))
res = s.substring(head, tail);
char temp = s.charAt(head);
tmpcount.put(temp, tmpcount.get(temp) - 1);
head++;
} else {
char temp = s.charAt(tail);
tmpcount.put(temp, tmpcount.getOrDefault(temp, 0) + 1);
tail++;
}
}
return res;
}
}