Minimum Window Substring 76
Description
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.
Hint
two points from one side
Method
fast and slow pointer when fast meet a character that in string t
Time & Space
o(n)
Code
public String minWindow(String s, String t) {
if (s.equals(t)){
return s;
}
int[] map = new int[128];
char[] ts = t.toCharArray();
char[] ss = s.toCharArray();
int begin = 0, end = 0;
int minLen = Integer.MAX_VALUE;
int head = 0;
int len = s.length();
int counter = t.length();
for (char c : ts){
map[c]++;
}
while (end < len){
if (map[ss[end++]]-- > 0){
counter--;
}
while (counter == 0){
if (end - begin < minLen){
minLen = end - begin;
head = begin;
}
if (map[ss[begin++]]++ == 0){
counter++;
}
}
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(head, head + minLen);
}