forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhyer0705.ts
More file actions
44 lines (34 loc) · 1.09 KB
/
hyer0705.ts
File metadata and controls
44 lines (34 loc) · 1.09 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
function minWindow(s: string, t: string): string {
const m = s.length;
const n = t.length;
if (m < n) return "";
let windowStart = 0;
let minLen = Infinity;
let substring = "";
let requiredChar = n;
const countCharMap = new Map<string, number>();
for (const ch of t) {
countCharMap.set(ch, (countCharMap.get(ch) || 0) + 1);
}
for (let windowEnd = 0; windowEnd < m; windowEnd++) {
const endChar = s[windowEnd];
if (countCharMap.has(endChar)) {
if (countCharMap.get(endChar)! > 0) requiredChar--;
countCharMap.set(endChar, (countCharMap.get(endChar) || 0) - 1);
}
while (requiredChar === 0) {
const currentLen = windowEnd - windowStart + 1;
if (currentLen < minLen) {
minLen = currentLen;
substring = s.substring(windowStart, windowEnd + 1);
}
const startChar = s[windowStart];
windowStart++;
if (countCharMap.has(startChar)) {
countCharMap.set(startChar, (countCharMap.get(startChar) || 0) + 1);
if (countCharMap.get(startChar)! > 0) requiredChar++;
}
}
}
return substring;
}