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"
.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
public class Solution {
public String minWindow(String s, String t) {
if (s == null || t == null || s.length() < t.length()) {
return "";
}
String res = "";
int[] map = new int[256];
for (int i = 0; i < t.length(); i++) {
map[t.charAt(i)]++;
}
int left = 0;
int right = 0;
int match = t.length();
int minLen = Integer.MAX_VALUE;
while (right != s.length()) {
map[s.charAt(right)]--;
if (map[s.charAt(right)] >= 0) {
match--;
}
if (match == 0) {
while (map[s.charAt(left)] < 0) {
map[s.charAt(left++)]++;
}
if (minLen > right - left + 1) {
minLen = right - left + 1;
res = s.substring(left, right+1);
}
match++;
map[s.charAt(left++)]++;
}
right++;
}
return res;
}
}