forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuraflower.js
More file actions
52 lines (44 loc) ยท 1.36 KB
/
uraflower.js
File metadata and controls
52 lines (44 loc) ยท 1.36 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
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
const minWindow = function (s, t) {
const counter = Array.from(t).reduce((obj, char) => {
obj[char] = (obj[char] || 0) + 1;
return obj;
}, {});
let lettersToSatisfy = Object.keys(counter).length;
let minStart = 0;
let minEnd = Infinity;
let start = 0;
for (let end = 0; end < s.length; end++) {
// s[end]๊ฐ t์ ํฌํจ๋ ๋ฌธ์์ธ ๊ฒฝ์ฐ
if (s[end] in counter) {
counter[s[end]]--;
// ํด๋น ๋ฌธ์๊ฐ ๋ฒ์ ์์ ๋ชจ๋ ํฌํจ๋ ๊ฒฝ์ฐ
if (counter[s[end]] === 0) {
lettersToSatisfy--;
}
}
// ํ์ฌ ๋ฒ์์ t ๋ด ๋ชจ๋ ๋ฌธ์๊ฐ ํฌํจ๋ ๊ฒฝ์ฐ
while (lettersToSatisfy === 0) {
// ๋ ์์ ๋ฒ์๋ก ์ ๋ต ๊ฐฑ์
if (end - start < minEnd - minStart) {
minStart = start;
minEnd = end;
}
// start ๋๋ฆฌ๊ธฐ
if (s[start] in counter) {
counter[s[start]]++;
if (counter[s[start]] > 0) {
lettersToSatisfy++;
}
}
start++;
}
}
return minEnd === Infinity ? '' : s.slice(minStart, minEnd + 1);
};
// ์๊ฐ๋ณต์ก๋: O(m) (m: s.length)
// ๊ณต๊ฐ๋ณต์ก๋: O(1)