forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclara-shin.js
More file actions
64 lines (54 loc) ยท 1.61 KB
/
clara-shin.js
File metadata and controls
64 lines (54 loc) ยท 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* ๋ฌธ์์ด s์์ ๋ฌธ์์ด t์ ๋ชจ๋ ๋ฌธ์(์ค๋ณต ํฌํจ)๋ฅผ ํฌํจํ๋ ๊ฐ์ฅ ์งง์ ๋ถ๋ถ ๋ฌธ์์ด์ ์ฐพ๋ ๋ฌธ์
* ์๊ฐ๋ณต์ก๋: O(m + n), ๊ณต๊ฐ๋ณต์ก๋: O(m + n)
*/
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function (s, t) {
if (s.length < t.length) return '';
// t์ ๊ฐ ๋ฌธ์๋ณ ํ์ํ ๊ฐ์๋ฅผ Map์ผ๋ก ์ ์ฅ
const need = new Map();
for (let char of t) {
need.set(char, (need.get(char) || 0) + 1);
}
let left = 0;
let right = 0;
let valid = 0; // ์กฐ๊ฑด์ ๋ง์กฑํ๋ ๋ฌธ์ ์ข
๋ฅ ์
let minLen = Infinity;
let start = 0;
// ํ์ฌ ์๋์ฐ์ ๋ฌธ์๋ณ ๊ฐ์
const window = new Map();
while (right < s.length) {
// ์๋์ฐ์ ๋ฌธ์ ์ถ๊ฐ
const rightChar = s[right];
right++;
// ํ์ํ ๋ฌธ์์ธ ๊ฒฝ์ฐ์๋ง ์ฒ๋ฆฌ
if (need.has(rightChar)) {
window.set(rightChar, (window.get(rightChar) || 0) + 1);
if (window.get(rightChar) === need.get(rightChar)) {
valid++;
}
}
// ์๋์ฐ ์ถ์ ์๋
while (valid === need.size) {
// ๋ ์์ ์๋์ฐ ๋ฐ๊ฒฌ์ ์
๋ฐ์ดํธ
if (right - left < minLen) {
start = left;
minLen = right - left;
}
// left๋ฅผ ์ด๋์ํค๋ฉฐ ์๋์ฐ์์ ๋ฌธ์ ์ ๊ฑฐ
const leftChar = s[left];
left++;
if (need.has(leftChar)) {
if (window.get(leftChar) === need.get(leftChar)) {
valid--;
}
window.set(leftChar, window.get(leftChar) - 1);
}
}
}
return minLen === Infinity ? '' : s.substring(start, start + minLen);
};