forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoobing.ts
More file actions
54 lines (44 loc) ยท 1.41 KB
/
soobing.ts
File metadata and controls
54 lines (44 loc) ยท 1.41 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
/**
* ๋ฌธ์ ์ค๋ช
* - ์ฃผ์ด์ง ๋ฌธ์์ด s์์ ์ฃผ์ด์ง ๋ฌธ์์ด t์ ๋ชจ๋ ๋ฌธ์๋ฅผ ํฌํจํ๋ ์ต์ ์๋์ฐ๋ฅผ ์ฐพ๋ ๋ฌธ์
*
* ์์ด๋์ด
* - ์ฌ๋ผ์ด๋ฉ ์๋์ฐ + ํด์๋งต(need, window)์ ์ด์ฉํ์ฌ ํ์ดํ๋ค.
* - ์ค๋ฅธ์ชฝ ํฌ์ธํฐ๋ฅผ ๋จผ์ ์ด๋ํ๊ณ , ์ด๋ฏธ ๋ชจ๋ ํฌํจ๋์ด ์๋ ๊ฒฝ์ฐ ์ผ์ชฝ ํฌ์ธํฐ๋ฅผ ์ด๋ํ์ฌ ์ต์ ์๋์ฐ๋ฅผ ์ฐพ๋๋ค.
*
*/
function minWindow(s: string, t: string): string {
if (t.length > s.length) return "";
const need = new Map<string, number>();
const window = new Map<string, number>();
for (const char of t) {
need.set(char, (need.get(char) || 0) + 1);
}
let have = 0;
let needSize = need.size;
let res = [-1, -1];
let resLen = Infinity;
let left = 0;
for (let right = 0; right < s.length; right++) {
const c = s[right];
window.set(c, (window.get(c) || 0) + 1);
if (need.has(c) && window.get(c) === need.get(c)) {
have++;
}
while (have === needSize) {
const currentResLen = right - left + 1;
if (currentResLen < resLen) {
res = [left, right];
resLen = currentResLen;
}
const lChar = s[left];
window.set(lChar, window.get(lChar)! - 1);
if (need.has(lChar) && window.get(lChar)! < need.get(lChar)!) {
have--;
}
left++;
}
}
const [start, end] = res;
return resLen === Infinity ? "" : s.slice(start, end + 1);
}