1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| class Solution { public String minWindow(String s, String t) { Map<Character, Integer> tmap = new HashMap<>(); for (char ch : t.toCharArray()) { putCharacter(tmap, ch); } Map<Character, Integer> map = new HashMap<>(); int length = s.length(); int minLength = -1; int windowStartIndex = 0; int begin = 0; int end = 0; while (end < length) { Character character = s.charAt(end); if (tmap.containsKey(character)) { putCharacter(map, character); if (isContaions(map, tmap)) { while (begin < end && needMove(map, tmap, s.charAt(begin))) { map.computeIfPresent(s.charAt(begin), (k, v) -> v - 1); begin++; } if (minLength == -1 || (end - begin + 1) < minLength) { minLength = end - begin + 1; windowStartIndex = begin; } } } else { if (minLength > 0 && end - begin + 1 > minLength) { reduceCharacter(map, s.charAt(begin)); begin++; while (begin < end && needMove(map, tmap, s.charAt(begin))) { map.computeIfPresent(s.charAt(begin), (k, v) -> v - 1); begin++; } } } end++; } if (minLength == -1) { return ""; } else { return s.substring(windowStartIndex, windowStartIndex + minLength); } } private boolean isContaions(Map<Character, Integer> sMap, Map<Character, Integer> tMap) { for (Map.Entry<Character, Integer> entry : tMap.entrySet()) { if (!sMap.containsKey(entry.getKey())) { return false; } if (sMap.get(entry.getKey()) < tMap.get(entry.getKey())) { return false; } } return true; } private boolean needMove(Map<Character, Integer> sMap, Map<Character, Integer> tMap, Character character) { if (!tMap.containsKey(character)) { return true; } if (!sMap.containsKey(character)) { return true; } return sMap.get(character) > tMap.get(character); }
private void putCharacter(Map<Character, Integer> map, Character character) { if (map.containsKey(character)) { map.compute(character, (k, v) -> v + 1); } else { map.put(character, 1); } } private void reduceCharacter(Map<Character, Integer> map, Character character) { if (map.containsKey(character)) { int num = map.get(character); if (num == 1) { map.remove(character); } else { map.put(character, num - 1); } } } }
|