forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0076-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
functionminWindow(s: string,t: string): string{
letminL=0;
letminR=s.length;
//create string t hashmap and needed
consttCount={};
letneeded=0;
for(leti=0;i<t.length;i++){
if(t[i]intCount)tCount[t[i]]++;
else{
tCount[t[i]]=1;
needed++;
}
}
//initialize winCount(empty)
constwinCount={};
letmatched=0;
letl=0;
for(letr=0;r<s.length;r++){
//update winCount with adding s[r]
if(s[r]inwinCount)winCount[s[r]]++;
elsewinCount[s[r]]=1;
//update matched
if(s[r]intCount&&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]intCount&&winCount[s[l]]===tCount[s[l]])matched--;
//update winCount with the removal of s[l]
winCount[s[l]]--;
if(winCount[s[l]]===0)deletewinCount[s[l]];
l++;
}
}
returnminR-minL+1>s.length ? '' : s.slice(minL,minR+1);
}