-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinWindowSubstring.java
54 lines (44 loc) · 1.56 KB
/
MinWindowSubstring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Minimum Window Substring
*
* <p>Given string S and string T, find a minimum window in S which will contain all characters in T
* in O(n) complexity.
*
* <p>e.g. S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC".
*
* <p>Note: If there is no such window in S that covers all characters in T, return the empty string "".
*
* <p>If there are multiple such windows, you are guaranteed that there will always be only one
* unique minimum window in S.
*
* <p>Solution O(n). Sliding window substring using two pointers.
*/
public class MinWindowSubstring {
public static void main(String[] args) {
System.out.println(new MinWindowSubstring().minWindow("ADOBECODEBANC", "ABC"));
}
public String minWindow(String s, String t) {
int[] map = new int[128];
for (char c : t.toCharArray()) {
map[c]++;
}
int left = 0, right = 0, minLeft = 0, minLength = Integer.MAX_VALUE, counter = t.length();
while (right < s.length()) {
final char c1 = s.charAt(right);
if (map[c1] > 0) counter--;
map[c1]--;
right++;
while (counter == 0) {
if (minLength > right - left) {
minLength = right - left;
minLeft = left;
}
final char c2 = s.charAt(left);
map[c2]++;
if (map[c2] > 0) counter++;
left++;
}
}
return minLength == Integer.MAX_VALUE ? "" : s.substring(minLeft, minLeft + minLength);
}
}