-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinimumWindowWithCharacters.java
38 lines (32 loc) · 1.2 KB
/
MinimumWindowWithCharacters.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
import java.util.HashMap;
public class MinimumWindowWithCharacters {
public String minWindow(String s, String t) {
HashMap<Character, Integer> map = new HashMap<>();
for (char x : t.toCharArray()) {
map.put(x, map.getOrDefault(x, 0) + 1);
}
int matched = 0;
int start = 0;
int minLen = s.length() + 1;
int subStr = 0;
for (int endWindow = 0; endWindow < s.length(); endWindow++) {
char right = s.charAt(endWindow);
if (map.containsKey(right)) {
map.put(right, map.get(right) - 1);
if (map.get(right) == 0) matched++;
}
while (matched == map.size()) {
if (minLen > endWindow - start + 1) {
minLen = endWindow - start + 1;
subStr = start;
}
char deleted = s.charAt(start++);
if (map.containsKey(deleted)) {
if (map.get(deleted) == 0) matched--;
map.put(deleted, map.get(deleted) + 1);
}
}
}
return minLen > s.length() ? "" : s.substring(subStr, subStr + minLen);
}
}