|
| 1 | +/* |
| 2 | +# Time Complexity: O(m * c) |
| 3 | + - c는 문자열에 사용된 문자의 가짓수(= 소문자 26 + 대문자 26) |
| 4 | + - 슬라이딩 윈도우로 s 전체를 훑는데 O(m)이 필요하고, 각 윈도우마다 t의 전체 문자가 포함되어 있는지 판단하는데 O(c)가 필요함 |
| 5 | +# Space Complexity: O(c) |
| 6 | + - sMap(슬라이딩 윈도우에 포함된 문자 카운트), tMap(문자열 t에 포함된 문자 카운트) 각각 O(c) |
| 7 | +*/ |
| 8 | +class Solution { |
| 9 | + public String minWindow(String s, String t) { |
| 10 | + Map<Character, Integer> sMap = new HashMap<>(); |
| 11 | + Map<Character, Integer> tMap = new HashMap<>(); |
| 12 | + for (int i = 0; i < t.length(); i++) { |
| 13 | + tMap.merge(t.charAt(i), 1, Integer::sum); |
| 14 | + } |
| 15 | + |
| 16 | + String ans = ""; |
| 17 | + int ansLen = Integer.MAX_VALUE; |
| 18 | + int l = 0; |
| 19 | + int r = 0; |
| 20 | + sMap.merge(s.charAt(0), 1, Integer::sum); |
| 21 | + while (l <= r) { |
| 22 | + if (included(sMap, tMap)) { |
| 23 | + if (r - l + 1 < ansLen) { |
| 24 | + ansLen = r - l + 1; |
| 25 | + ans = s.substring(l, r + 1); |
| 26 | + } |
| 27 | + sMap.merge(s.charAt(l), -1, Integer::sum); |
| 28 | + l++; |
| 29 | + } else { |
| 30 | + r++; |
| 31 | + if (r >= s.length()) break; |
| 32 | + sMap.merge(s.charAt(r), 1, Integer::sum); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + while (l <= r && included(sMap, tMap)) { |
| 37 | + if (r - l + 1 > ansLen) { |
| 38 | + ansLen = r - l + 1; |
| 39 | + ans = s.substring(l, r + 1); |
| 40 | + } |
| 41 | + sMap.merge(s.charAt(l), -1, Integer::sum); |
| 42 | + l++; |
| 43 | + } |
| 44 | + |
| 45 | + return ans; |
| 46 | + } |
| 47 | + |
| 48 | + private boolean included(Map<Character, Integer> sMap, Map<Character, Integer> tMap) { |
| 49 | + for (Character key : tMap.keySet()) { |
| 50 | + if (!sMap.containsKey(key) || sMap.get(key) < tMap.get(key)) return false; |
| 51 | + } |
| 52 | + return true; |
| 53 | + } |
| 54 | +} |
0 commit comments