Skip to content

Commit 0e0fd4f

Browse files
authored
Update Minimum Window Substring.java
1 parent 3d8dca2 commit 0e0fd4f

File tree

1 file changed

+33
-33
lines changed

1 file changed

+33
-33
lines changed

Hard/Minimum Window Substring.java

Lines changed: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
11
class Solution {
2-
public String minWindow(String s, String t) {
3-
Map<Character, Integer> map = new HashMap<>();
4-
for (char c : t.toCharArray()) {
5-
map.put(c, map.getOrDefault(c, 0) + 1);
6-
}
7-
int count = map.size();
8-
int start = 0;
9-
int end = 0;
10-
int minWindowLength = Integer.MAX_VALUE;
11-
int minWindowStart = 0;
12-
int minWindowEnd = 0;
13-
while (end < s.length()) {
14-
char c = s.charAt(end++);
15-
if (map.containsKey(c)) {
16-
map.put(c, map.get(c) - 1);
17-
if (map.get(c) == 0) {
18-
count--;
19-
}
20-
}
21-
while (count == 0 && start < end) {
22-
if (end - start < minWindowLength) {
23-
minWindowLength = end - start;
24-
minWindowStart = start;
25-
minWindowEnd = end;
2+
public String minWindow(String s, String t) {
3+
Map<Character, Integer> map = new HashMap<>();
4+
for (char c : t.toCharArray()) {
5+
map.put(c, map.getOrDefault(c, 0) + 1);
266
}
27-
char temp = s.charAt(start++);
28-
if (map.containsKey(temp)) {
29-
map.put(temp, map.get(temp) + 1);
30-
if (map.get(temp) == 1) {
31-
count++;
32-
}
7+
int targetSize = map.size();
8+
int start = 0;
9+
int minLength = Integer.MAX_VALUE;
10+
int minStart = -1;
11+
int minEnd = -1;
12+
int n = s.length();
13+
for (int i = 0; i < n; i++) {
14+
if (map.containsKey(s.charAt(i))) {
15+
map.put(s.charAt(i), map.get(s.charAt(i)) - 1);
16+
if (map.get(s.charAt(i)) == 0) {
17+
targetSize--;
18+
}
19+
}
20+
while (start <= i && targetSize == 0) {
21+
int currLength = i - start;
22+
if (minLength > currLength) {
23+
minLength = currLength;
24+
minStart = start;
25+
minEnd = i + 1;
26+
}
27+
if (map.containsKey(s.charAt(start))) {
28+
map.put(s.charAt(start), map.get(s.charAt(start)) + 1);
29+
if (map.get(s.charAt(start)) == 1) {
30+
targetSize++;
31+
}
32+
}
33+
start++;
34+
}
3335
}
34-
}
36+
return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minEnd);
3537
}
36-
return s.substring(minWindowStart, minWindowEnd);
37-
}
3838
}

0 commit comments

Comments
 (0)