Skip to content

Commit 95c5bf3

Browse files
authored
Update Minimum Window Substring.java
1 parent 0256a21 commit 95c5bf3

File tree

1 file changed

+33
-38
lines changed

1 file changed

+33
-38
lines changed

Hard/Minimum Window Substring.java

Lines changed: 33 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +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));
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;
626
}
7-
8-
int start = 0;
9-
int end = 0;
10-
int count = map.size();
11-
int minLen = Integer.MAX_VALUE;
12-
String ans = "";
13-
14-
while (end < s.length()) {
15-
if (map.containsKey(s.charAt(end))) {
16-
map.put(s.charAt(end), map.get(s.charAt(end)) - 1);
17-
if (map.get(s.charAt(end)) == 0) {
18-
count--;
19-
}
20-
}
21-
22-
end++;
23-
24-
while (count == 0) {
25-
if (end - start < minLen) {
26-
minLen = end - start;
27-
ans = s.substring(start, end);
28-
}
29-
30-
if (map.containsKey(s.charAt(start))) {
31-
map.put(s.charAt(start), map.get(s.charAt(start)) + 1);
32-
if (map.get(s.charAt(start)) > 0) {
33-
count++;
34-
}
35-
}
36-
37-
start++;
38-
}
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+
}
3933
}
40-
41-
return ans;
34+
}
4235
}
36+
return s.substring(minWindowStart, minWindowEnd);
37+
}
4338
}

0 commit comments

Comments
 (0)