forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum Window Substring.java
More file actions
38 lines (38 loc) · 1.02 KB
/
Minimum Window Substring.java
File metadata and controls
38 lines (38 loc) · 1.02 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
class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
for (char c : t.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
int count = map.size();
int start = 0;
int end = 0;
int minWindowLength = Integer.MAX_VALUE;
int minWindowStart = 0;
int minWindowEnd = 0;
while (end < s.length()) {
char c = s.charAt(end++);
if (map.containsKey(c)) {
map.put(c, map.get(c) - 1);
if (map.get(c) == 0) {
count--;
}
}
while (count == 0 && start < end) {
if (end - start < minWindowLength) {
minWindowLength = end - start;
minWindowStart = start;
minWindowEnd = end;
}
char temp = s.charAt(start++);
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
if (map.get(temp) == 1) {
count++;
}
}
}
}
return s.substring(minWindowStart, minWindowEnd);
}
}