Skip to content

Commit 3ca602b

Browse files
authored
[ PS ] : Minimum Window Substring
1 parent 5e67846 commit 3ca602b

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} t
4+
* @return {string}
5+
*/
6+
const minWindow = function (s, t) {
7+
const counter = Array.from(t).reduce((obj, char) => {
8+
obj[char] = (obj[char] || 0) + 1;
9+
return obj;
10+
}, {});
11+
12+
let lettersToSatisfy = Object.keys(counter).length;
13+
let minStart = 0;
14+
let minEnd = Infinity;
15+
16+
let start = 0;
17+
for (let end = 0; end < s.length; end++) {
18+
// s[end]๊ฐ€ t์— ํฌํ•จ๋œ ๋ฌธ์ž์ธ ๊ฒฝ์šฐ
19+
if (s[end] in counter) {
20+
counter[s[end]]--;
21+
22+
// ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ๋ฒ”์œ„ ์•ˆ์— ๋ชจ๋‘ ํฌํ•จ๋œ ๊ฒฝ์šฐ
23+
if (counter[s[end]] === 0) {
24+
lettersToSatisfy--;
25+
}
26+
}
27+
28+
// ํ˜„์žฌ ๋ฒ”์œ„์— t ๋‚ด ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ ํฌํ•จ๋œ ๊ฒฝ์šฐ
29+
while (lettersToSatisfy === 0) {
30+
// ๋” ์ž‘์€ ๋ฒ”์œ„๋กœ ์ •๋‹ต ๊ฐฑ์‹ 
31+
if (end - start < minEnd - minStart) {
32+
minStart = start;
33+
minEnd = end;
34+
}
35+
36+
// start ๋Š˜๋ฆฌ๊ธฐ
37+
if (s[start] in counter) {
38+
counter[s[start]]++;
39+
if (counter[s[start]] > 0) {
40+
lettersToSatisfy++;
41+
}
42+
}
43+
44+
start++;
45+
}
46+
}
47+
48+
return minEnd === Infinity ? '' : s.slice(minStart, minEnd + 1);
49+
};
50+
51+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(m) (m: s.length)
52+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(1)

0 commit comments

Comments
ย (0)