|
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); |
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); |
26 | 6 | }
|
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 | + } |
33 | 35 | }
|
34 |
| - } |
| 36 | + return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minEnd); |
35 | 37 | }
|
36 |
| - return s.substring(minWindowStart, minWindowEnd); |
37 |
| - } |
38 | 38 | }
|
0 commit comments