|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +class Solution { |
| 5 | + |
| 6 | + // 시간복잡도: O(n), 공간복잡도 O(1) |
| 7 | + public String minWindow(String s, String t) { |
| 8 | + |
| 9 | + int strLength = s.length(); |
| 10 | + int targetLength = t.length(); |
| 11 | + |
| 12 | + // 목표 분자열이 주어진 문자열보다 길다면 부분 문자열로 볼 수 없음 |
| 13 | + if (targetLength > strLength) { |
| 14 | + return ""; |
| 15 | + } |
| 16 | + |
| 17 | + // 목표 문자열에 필요한 문자와 그 개수를 담는 맵 |
| 18 | + Map<Character, Integer> charMap = new HashMap<>(); |
| 19 | + |
| 20 | + for (char c : t.toCharArray()) { |
| 21 | + charMap.put(c, charMap.getOrDefault(c, 0) + 1); |
| 22 | + } |
| 23 | + |
| 24 | + // 투 포인터 선언 |
| 25 | + int left = 0; |
| 26 | + int right = 0; |
| 27 | + int minWindowLength = Integer.MAX_VALUE; |
| 28 | + int minWindowStart = 0; // 최소 윈도우 시작 위치 |
| 29 | + int remaining = targetLength; |
| 30 | + |
| 31 | + while (right < strLength) { |
| 32 | + |
| 33 | + Character end = s.charAt(right); |
| 34 | + |
| 35 | + if (charMap.containsKey(end)) { |
| 36 | + charMap.put(end, charMap.get(end) - 1); |
| 37 | + if (charMap.get(end) >= 0) { |
| 38 | + remaining--; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // target 문자열의 모든 문자를 찾았다면 left 포인터 이동하면서 |
| 43 | + // 최소 윈도우 찾기 시작 |
| 44 | + while (remaining == 0) { |
| 45 | + if (right - left + 1 < minWindowLength) { |
| 46 | + minWindowLength = right - left + 1; |
| 47 | + minWindowStart = left; |
| 48 | + } |
| 49 | + |
| 50 | + char startChar = s.charAt(left); |
| 51 | + if (charMap.containsKey(startChar)) { |
| 52 | + charMap.put(startChar, charMap.get(startChar) + 1); |
| 53 | + if (charMap.get(startChar) > 0) { |
| 54 | + remaining++; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + left++; |
| 59 | + } |
| 60 | + |
| 61 | + right++; |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + return minWindowLength == Integer.MAX_VALUE ? "" |
| 66 | + : s.substring(minWindowStart, minWindowStart + minWindowLength); |
| 67 | + |
| 68 | + } |
| 69 | +} |
| 70 | + |
0 commit comments