Skip to content

Commit f7a6254

Browse files
committed
minWindow
1 parent 5be49c6 commit f7a6254

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
| 0070 | [climbStairs](./code/0070_climbStairs) || DP | |
3232
| 0074 | [searchMatrix](./code/0074_searchMatrix) | ⭐⭐ | Binary Search | |
3333
| 0075 | [sortColors](./code/0075_sortColors) | ⭐⭐ | Two Pointers, Array | 2️⃣✅ |
34+
| 0076 | [minWindow](./code/0076_minWindow) | ⭐⭐⭐ | Sliding Window | 1️⃣ |
3435
| 0078 | [subsets](./code/0078_subsets) | ⭐⭐ | Array, Backtracking | |
3536
| 0086 | [partition](./code/0086_partition) | ⭐⭐ | Linked List | |
3637
| 0088 | [merge](./code/0088_merge) || Array, Two Pointers | |
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} t
4+
* @return {string}
5+
*/
6+
var minWindow = function (s, t) {
7+
let minLen = s.length + 1;
8+
let start = s.length;
9+
let map = new Map();
10+
11+
for (const c of t) {
12+
map[c] ? map[c]++ : map[c] = 1;
13+
}
14+
15+
let need = Object.keys(map).length;
16+
let l = 0, r = 0;
17+
while (r < s.length) {
18+
if (map[s[r]] !== undefined) {
19+
map[s[r]]--;
20+
}
21+
if (map[s[r]] === 0) {
22+
need--;
23+
}
24+
while (need === 0) {
25+
if (r - l + 1 < minLen) {
26+
minLen = Math.min(minLen, r - l + 1);
27+
start = l;
28+
}
29+
if (map[s[l]] !== undefined) {
30+
map[s[l]]++;
31+
}
32+
if (map[s[l]] > 0) {
33+
need++;
34+
}
35+
l++;
36+
}
37+
r++;
38+
}
39+
if (start === s.length) {
40+
return '';
41+
}
42+
return s.substring(start, start + minLen);
43+
};
44+
45+
console.log(minWindow("a", "a"));

0 commit comments

Comments
 (0)