-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0076-minimum-window-substring.java
36 lines (32 loc) · 1.16 KB
/
0076-minimum-window-substring.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
class Solution {
//sliding window
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);
}
}