Skip to content

Commit 58fd46f

Browse files
committed
add solution : 76. Minimum Window Substring
1 parent bfd79dd commit 58fd46f

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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

Comments
Β (0)