forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumWindowSubstring.java
More file actions
64 lines (54 loc) · 1.77 KB
/
MinimumWindowSubstring.java
File metadata and controls
64 lines (54 loc) · 1.77 KB
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
55
56
57
58
59
60
61
62
63
64
package com.thealgorithms.strings;
/**
* Minimum Window Substring
*
* Given two strings s and t, return the minimum window substring of s such that
* every character in t (including duplicates) is included in the window.
*
* If there is no such substring, return an empty string "".
*
* Approach: Sliding Window + Frequency Table.
*
* Time complexity: O(n + m)
* Space complexity: O(1) for ASCII characters.
*
* Reference: https://en.wikipedia.org/wiki/Minimum_window_substring
*/
public final class MinimumWindowSubstring {
private MinimumWindowSubstring() {
throw new UnsupportedOperationException("Utility class");
}
public static String minWindow(String s, String t) {
if (s == null || t == null || s.length() < t.length() || t.isEmpty()) {
return "";
}
int[] need = new int[256];
for (char c : t.toCharArray()) {
need[c]++;
}
int required = 0;
for (int i = 0; i < 256; i++) {
if (need[i] > 0) required++;
}
int l = 0, r = 0, formed = 0;
int[] window = new int[256];
int minLen = Integer.MAX_VALUE, minLeft = 0;
while (r < s.length()) {
char c = s.charAt(r);
window[c]++;
if (need[c] > 0 && window[c] == need[c]) formed++;
while (l <= r && formed == required) {
if (r - l + 1 < minLen) {
minLen = r - l + 1;
minLeft = l;
}
char d = s.charAt(l);
window[d]--;
if (need[d] > 0 && window[d] < need[d]) formed--;
l++;
}
r++;
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(minLeft, minLeft + minLen);
}
}