forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0076-minimum-window-substring.ts
48 lines (41 loc) · 1.27 KB
/
0076-minimum-window-substring.ts
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
function minWindow(s: string, t: string): string {
let minL = 0;
let minR = s.length;
//create string t hashmap and needed
const tCount = {};
let needed = 0;
for (let i = 0; i < t.length; i++) {
if (t[i] in tCount) tCount[t[i]]++;
else {
tCount[t[i]] = 1;
needed++;
}
}
//initialize winCount(empty)
const winCount = {};
let matched = 0;
let l = 0;
for (let r = 0; r < s.length; r++) {
//update winCount with adding s[r]
if (s[r] in winCount) winCount[s[r]]++;
else winCount[s[r]] = 1;
//update matched
if (s[r] in tCount && winCount[s[r]] === tCount[s[r]]) matched++;
//the window is valid
while (matched === needed) {
//update min
if (r - l + 1 < minR - minL + 1) {
minL = l;
minR = r;
}
//remove l
//update matched
if (s[l] in tCount && winCount[s[l]] === tCount[s[l]]) matched--;
//update winCount with the removal of s[l]
winCount[s[l]]--;
if (winCount[s[l]] === 0) delete winCount[s[l]];
l++;
}
}
return minR - minL + 1 > s.length ? '' : s.slice(minL, minR + 1);
}