|
2 | 2 | import java.util.Map; |
3 | 3 |
|
4 | 4 | public class Solution76 { |
| 5 | + private Map<Character, Integer> tMap; |
| 6 | + |
5 | 7 | public String minWindow(String s, String t) { |
6 | | - if (s.length() < t.length()) { |
| 8 | + int n = s.length(); |
| 9 | + int m = t.length(); |
| 10 | + if (n < m) { |
7 | 11 | return ""; |
8 | 12 | } |
9 | | - Map<Character, Integer> sCntMap = new HashMap<>(); |
10 | | - Map<Character, Integer> tCntMap = new HashMap<>(); |
| 13 | + tMap = new HashMap<>(); |
11 | 14 | for (char ch : t.toCharArray()) { |
12 | | - tCntMap.put(ch, tCntMap.getOrDefault(ch, 0) + 1); |
| 15 | + tMap.put(ch, tMap.getOrDefault(ch, 0) + 1); |
13 | 16 | } |
14 | 17 |
|
15 | | - // 双指针-滑动窗口 |
16 | | - int left = 0; |
17 | | - int right = 0; |
18 | | - // 此处有坑,不能直接 s.length() 因为存在 s = "a", t = "b" 用例 |
19 | | - int ansLen = Integer.MAX_VALUE; |
20 | | - int ansStart = 0; |
21 | | - while (right < s.length()) { |
22 | | - // 右指针右移 增加字符 |
23 | | - char addCh = s.charAt(right); |
24 | | - sCntMap.put(addCh, sCntMap.getOrDefault(addCh, 0) + 1); |
25 | | - right++; |
26 | | - |
27 | | - // 左指针右移 |
28 | | - while (checkInclusion(sCntMap, tCntMap)) { |
29 | | - int curLen = right - left; |
30 | | - if (curLen < ansLen) { |
31 | | - ansLen = curLen; |
32 | | - ansStart = left; |
| 18 | + Map<Character, Integer> sMap = new HashMap<>(); |
| 19 | + int left = 0, right = 0; |
| 20 | + int ansLen = n + 1; |
| 21 | + int ansL = 0; |
| 22 | + while (right < n) { |
| 23 | + char ch = s.charAt(right); |
| 24 | + sMap.put(ch, sMap.getOrDefault(ch, 0) + 1); |
| 25 | + while (check(sMap)) { |
| 26 | + if (ansLen > right - left + 1) { |
| 27 | + ansLen = right - left + 1; |
| 28 | + ansL = left; |
33 | 29 | } |
34 | | - // 移除字符 |
35 | | - char rmCh = s.charAt(left); |
36 | | - sCntMap.put(rmCh, sCntMap.getOrDefault(rmCh, 0) - 1); |
| 30 | + char rm = s.charAt(left); |
| 31 | + sMap.put(rm, sMap.get(rm) - 1); |
37 | 32 | left++; |
38 | 33 | } |
| 34 | + right++; |
39 | 35 | } |
40 | | - return ansLen == Integer.MAX_VALUE ? "" : s.substring(ansStart, ansStart + ansLen); |
| 36 | + return (ansLen == n + 1) ? "" : s.substring(ansL, ansL + ansLen); |
41 | 37 | } |
42 | 38 |
|
43 | | - // window 是否包含 need 的字符 |
44 | | - private boolean checkInclusion(Map<Character, Integer> window, Map<Character, Integer> need) { |
45 | | - for (Map.Entry<Character, Integer> entry : need.entrySet()) { |
46 | | - char curCh = entry.getKey(); |
47 | | - if (window.getOrDefault(curCh, 0) < entry.getValue()) { |
| 39 | + // sMap 是否完全覆盖 tMap |
| 40 | + private boolean check(Map<Character, Integer> sMap) { |
| 41 | + for (Map.Entry<Character, Integer> entry : tMap.entrySet()) { |
| 42 | + char ch = entry.getKey(); |
| 43 | + if (sMap.getOrDefault(ch, 0) < entry.getValue()) { |
48 | 44 | return false; |
49 | 45 | } |
50 | 46 | } |
|
0 commit comments