-
Notifications
You must be signed in to change notification settings - Fork 1
/
MinimumWindowSubstr.java
46 lines (40 loc) · 2.21 KB
/
MinimumWindowSubstr.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
import java.util.*;
class MinimumWindowSubstr {
public static String findSubstring(String str, String pattern) {
int windowStart = 0, matched = 0, minLength = str.length() + 1, subStrStart = 0;
Map<Character, Integer> charFrequencyMap = new HashMap<>();
for (char chr : pattern.toCharArray())
charFrequencyMap.put(chr, charFrequencyMap.getOrDefault(chr, 0) + 1);
// try to extend the range [windowStart, windowEnd]
for (int windowEnd = 0; windowEnd < str.length(); windowEnd++) {
char rightChar = str.charAt(windowEnd);
if (charFrequencyMap.containsKey(rightChar)) {
charFrequencyMap.put(rightChar, charFrequencyMap.get(rightChar) - 1);
if (charFrequencyMap.get(rightChar) >= 0) // count every matching of a character
matched++;
}
// shrink the window if we can, finish as soon as we remove a matched character
while (matched == pattern.length()) {
if (minLength > windowEnd - windowStart + 1) {
minLength = windowEnd - windowStart + 1;
subStrStart = windowStart;
}
char leftChar = str.charAt(windowStart++);
if (charFrequencyMap.containsKey(leftChar)) {
// note that we could have redundant matching characters, therefore we'll decrement the
// matched count only when a useful occurrence of a matched character is going out of the window
if (charFrequencyMap.get(leftChar) == 0)
matched--;
charFrequencyMap.put(leftChar, charFrequencyMap.get(leftChar) + 1);
}
}
}
return minLength > str.length() ? "" : str.substring(subStrStart, subStrStart + minLength);
}
public static void main(String[] args) {
System.out.println(MinimumWindowSubstr.findSubstring("aabdec", "abc"));
System.out.println(MinimumWindowSubstr.findSubstring("aabdec", "abac"));
System.out.println(MinimumWindowSubstr.findSubstring("abdbca", "abc"));
System.out.println(MinimumWindowSubstr.findSubstring("adcad", "abc"));
}
}