forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgwbaik9717.js
More file actions
75 lines (60 loc) · 1.21 KB
/
gwbaik9717.js
File metadata and controls
75 lines (60 loc) · 1.21 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
65
66
67
68
69
70
71
72
73
74
75
// n: len(s), m: len(t)
// Time complexity: O(n+m)
// Space complexity: O(n+m)
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function (s, t) {
let i = 0;
let j = 0;
const current = new Map();
const target = new Map();
current.set(s[i], 1);
for (const chr of t) {
if (target.has(chr)) {
target.set(chr, target.get(chr) + 1);
continue;
}
target.set(chr, 1);
}
let answer = null;
while (i < s.length) {
let pass = true;
for (const [key, value] of target) {
if (!current.has(key)) {
pass = false;
break;
}
if (current.get(key) < value) {
pass = false;
break;
}
}
if (pass) {
if (!answer) {
answer = s.slice(i, j + 1);
}
if (answer && j - i + 1 < answer.length) {
answer = s.slice(i, j + 1);
}
current.set(s[i], current.get(s[i]) - 1);
if (current.get(s[i]) === 0) {
current.delete(s[i]);
}
i++;
continue;
}
if (j < s.length) {
j++;
current.set(s[j], (current.get(s[j]) || 0) + 1);
} else {
break;
}
}
if (answer === null) {
return "";
}
return answer;
};