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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Difficulty: hard
Solution: Use hashtable to track the number of used character in t
import java.util.Hashtable;
public class Solution {
public String minWindow(String s, String t) {
if(t.length() > s.length())
return "";
int index1 = -1, index2 = -1, ans = Integer.MAX_VALUE;
Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>();
for(int i = 0; i < t.length(); i++){
if(ht.containsKey(t.charAt(i))){
ht.put(t.charAt(i), ht.get(t.charAt(i)) + 1);
}
else{
ht.put(t.charAt(i), 1);
}
}
int len = s.length();
int left = 0, right = 0;
int currLen = 0;
while(right < len){
if(ht.containsKey(s.charAt(right))){
ht.put(s.charAt(right), ht.get(s.charAt(right)) - 1);
currLen++;
if(currLen == t.length()){
return s.substring(left, right + 1);
}
break;
}
right++;
left++;
}
while(right < len){
if(currLen < t.length()){
if(right == len -1){
break;
}
right++;
if(ht.containsKey(s.charAt(right))){
ht.put(s.charAt(right), ht.get(s.charAt(right)) - 1);
if(ht.get(s.charAt(right)) >= 0){
currLen++;
}
}
}
else{
if(left == len -1 || right == left){
break;
}
if(ht.containsKey(s.charAt(left))){
ht.put(s.charAt(left), ht.get(s.charAt(left)) + 1);
if(ht.get(s.charAt(left)) > 0){
currLen--;
}
}
left++;
}
if(currLen == t.length() && ans > (right - left)){
ans = right - left;
index1 = left;
index2 = right;
}
}
if(index1 == -1 && index2 == -1)
return "";
return s.substring(index1, index2 + 1);
}
}