|
1 | 1 | 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; |
6 | 26 | }
|
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 | + } |
39 | 33 | }
|
40 |
| - |
41 |
| - return ans; |
| 34 | + } |
42 | 35 | }
|
| 36 | + return s.substring(minWindowStart, minWindowEnd); |
| 37 | + } |
43 | 38 | }
|
0 commit comments