Minimum Window Substring
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.
Analysis
- Keep a sliding window
- Update window size when all chars in t is found in s
- Keep the start index of sliding window as small as possible
Code
public class Solution {
public String minWindow(String s, String t) {
if (s.length()==0 || t.length()==0 || s.length()<t.length() || s==null || t==null) {return "";}
int left = t.length(), start = 0, end = s.length()-1;
Deque<Integer> queue = new LinkedList<Integer>();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i=0;i<t.length();i++){
char c= t.charAt(i);
map.put(c,map.containsKey(c)?map.get(c)+1:1);
}
for (int i=0; i<s.length(); i++){
char c = s.charAt(i);
if (!map.containsKey(c)) continue;
queue.add(i);
if (map.get(c)>0) left--;
map.put(c, map.get(c)-1);
while (map.get(s.charAt(queue.peek()))<0){
char rep = s.charAt(queue.peek());
queue.poll();
map.put(rep, map.get(rep)+1);
}
if (left==0){
if (queue.peekLast()-queue.peek() < end -start){
start = queue.peek();
end = queue.peekLast();
}
}
}
if (left!=0) {return "";}
else return s.substring(start, end+1);
}
}
Note
Reference