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.
import java.util.HashMap;
public class Solution {
public String minWindow(String S, String T) {
if(S == null || S.length() == 0) return S;
if(T == null || T.length() == 0) return "";
String minWindow = "";
HashMap<Character, Integer> toFind = new HashMap<Character, Integer>();
for(int i = 0; i < T.length(); i++){
char c = T.charAt(i);
if(toFind.containsKey(c)){
toFind.put(c, toFind.get(c) + 1);
} else {
toFind.put(c, 1);
}
}
HashMap<Character, Integer> found = new HashMap<Character, Integer>();
int count = 0;
int leftBound = 0;
for(int i = 0; i < S.length(); i++){
char c = S.charAt(i);
if(!toFind.containsKey(c)){
continue;
}
if(found.containsKey(c)){
found.put(c, found.get(c) + 1);
} else {
found.put(c, 1);
}
if(found.get(c) <= toFind.get(c)) count++;
if(count == T.length()){
while(leftBound < i){
char left = S.charAt(leftBound);
if(!toFind.containsKey(left)){
leftBound++;
continue;
}
if(found.get(left) > toFind.get(left)){
leftBound++;
found.put(left, found.get(left) - 1);
continue;
}
break;
}
if(minWindow == "" || i - leftBound + 1 < minWindow.length()){
minWindow = S.substring(leftBound, i + 1);
}
}
}
return minWindow;
}
}