forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHC-kang.ts
More file actions
44 lines (37 loc) ยท 867 Bytes
/
HC-kang.ts
File metadata and controls
44 lines (37 loc) ยท 867 Bytes
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
/**
* https://leetcode.com/problems/minimum-window-substring
* T.C. O(s + t)
* S.C. O(t)
*/
function minWindow(s: string, t: string): string {
let minLow = 0;
let minHigh = s.length;
const counts: Record<string, number> = {};
for (const c of t) {
counts[c] = (counts[c] || 0) + 1;
}
let included = 0;
let low = 0;
for (let high = 0; high < s.length; high++) {
if (counts[s[high]]) {
if (counts[s[high]] > 0) {
included++;
}
counts[s[high]]--;
}
while (included === t.length) {
if (high - low < minHigh - minLow) {
minLow = low;
minHigh = high;
}
if (counts[s[low]]) {
counts[s[low]]++;
if (counts[s[low]] > 0) {
included--;
}
}
low++;
}
}
return minHigh === s.length ? '' : s.substring(minLow, minHigh + 1);
}