Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC"
.
public String minWindow(String s, String t) {
if (s == null || s.length() == 0) return "";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
int l = 0;
int cnt = 0;
int start = 0;
int minLength = s.length() + 1;
for (int r = 0; r < s.length(); r++) {
if (map.containsKey(s.charAt(r))) {
map.put(s.charAt(r), map.get(s.charAt(r)) - 1);
if (map.get(s.charAt(r)) >= 0) cnt++;
while (cnt == t.length()) {
if (r - l + 1 < minLength) {
minLength = r - l + 1;
start = l;
}
if (map.containsKey(s.charAt(l))) {
map.put(s.charAt(l), map.get(s.charAt(l)) + 1);
if (map.get(s.charAt(l)) > 0) cnt--;
}
l++;
}
}
}
return minLength > s.length() ? "" : s.substring(start, start + minLength);
}