|
| 1 | +/** |
| 2 | + * @link https://leetcode.com/problems/minimum-window-substring/description/ |
| 3 | + * μ κ·Ό λ°©λ² : 2κ°μ ν¬μΈν° νμ©ν΄μ μ¬λΌμ΄λ© μλμ° λ°©μ μ¬μ© |
| 4 | + * - tμ λ¬Έμλ₯Ό λ§΅μ μ μ₯ν΄μ κ°μ κΈ°λ‘ |
| 5 | + * - right ν¬μΈν°λ‘ tμ λͺ¨λ λ¬Έμ ν¬ν¨ν λκΉμ§ μλμ° νμ₯ |
| 6 | + * - λͺ¨λ λ¬Έμ ν¬ν¨νλ©΄, left ν¬μΈν°λ‘ μ΅μ μλμ° μ°Ύμ λκΉμ§ μλμ° μΆμ |
| 7 | + * - 'νμ₯ => μΆμ => μ΅μ μλμ° μ
λ°μ΄νΈ' μ΄ κ³Όμ μ λ°λ³΅ |
| 8 | + * |
| 9 | + * μκ°λ³΅μ‘λ : O(n) |
| 10 | + * - nμ sμ κΈΈμ΄, κ° λ¬Έμ μ΅λ 2ν λ°©λ¬Έ (νμ₯ + μΆμ) |
| 11 | + * |
| 12 | + * 곡κ°λ³΅μ‘λ : O(n) |
| 13 | + * - μ΅μ
μ κ²½μ°, μλμ°μ sμ λͺ¨λ λ¬Έμκ° μ μ₯λ¨ |
| 14 | + */ |
| 15 | +function minWindow(s: string, t: string): string { |
| 16 | + const targetCharCount = new Map<string, number>(); |
| 17 | + |
| 18 | + // tμ λ¬Έμ κ°μ μΉ΄μ΄νΈ |
| 19 | + for (const char of t) { |
| 20 | + targetCharCount.set(char, (targetCharCount.get(char) ?? 0) + 1); |
| 21 | + } |
| 22 | + |
| 23 | + const requiredUniqueChars = targetCharCount.size; |
| 24 | + let matchedUniqueChars = 0; |
| 25 | + const windowCharCount = new Map<string, number>(); |
| 26 | + |
| 27 | + let minWindow = ""; |
| 28 | + let minWindowLength = Infinity; |
| 29 | + |
| 30 | + let left = 0, |
| 31 | + right = 0; |
| 32 | + |
| 33 | + while (right < s.length) { |
| 34 | + const char = s[right]; |
| 35 | + windowCharCount.set(char, (windowCharCount.get(char) ?? 0) + 1); |
| 36 | + |
| 37 | + // tμ μνλ λ¬Έμμ΄λ©΄μ, λ¬Έμ κ°μκ° κ°μ κ²½μ° |
| 38 | + if ( |
| 39 | + targetCharCount.has(char) && |
| 40 | + targetCharCount.get(char) === windowCharCount.get(char) |
| 41 | + ) |
| 42 | + matchedUniqueChars++; |
| 43 | + |
| 44 | + while (matchedUniqueChars === requiredUniqueChars) { |
| 45 | + const windowLength = right - left + 1; |
| 46 | + |
| 47 | + // μ΅μ μλμ° μ
λ°μ΄νΈ |
| 48 | + if (windowLength < minWindowLength) { |
| 49 | + minWindowLength = windowLength; |
| 50 | + minWindow = s.substring(left, right + 1); |
| 51 | + } |
| 52 | + |
| 53 | + const leftChar = s[left]; |
| 54 | + windowCharCount.set(leftChar, windowCharCount.get(leftChar)! - 1); |
| 55 | + |
| 56 | + //μΆμλ‘ μλμ° λ΄μ tλ¬Έμκ° κ°μνμΌλ©΄ matchedUniqueChars κ°μ |
| 57 | + if (windowCharCount.get(leftChar)! < targetCharCount.get(leftChar)!) |
| 58 | + matchedUniqueChars--; |
| 59 | + |
| 60 | + // μλμ° μΆμ |
| 61 | + left++; |
| 62 | + } |
| 63 | + |
| 64 | + // μλμ° νμ₯ |
| 65 | + right++; |
| 66 | + } |
| 67 | + |
| 68 | + return minWindow; |
| 69 | +} |
0 commit comments