Skip to content

Commit 339c536

Browse files
committed
added js 76-min-window
1 parent 93232c6 commit 339c536

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
var minWindow = function (str, target) {
2+
const hash = target.split('').reduce((acc, val) => {
3+
if (!acc[val]) acc[val] = 0;
4+
acc[val] += 1;
5+
return acc;
6+
}, {})
7+
8+
let start = 0;
9+
let min = Infinity;
10+
let matched = 0;
11+
let subStringStart = null;
12+
13+
for (let i = 0; i < str.length; i++) {
14+
let rightChar = str[i];
15+
16+
if (rightChar in hash) hash[rightChar] -= 1;
17+
if (hash[rightChar] >= 0) matched += 1;
18+
19+
while (matched === target.length) {
20+
if (i - start + 1 < min) {
21+
subStringStart = start;
22+
min = i - start + 1;
23+
}
24+
25+
let leftChar = str[start];
26+
start += 1;
27+
28+
if (leftChar in hash) {
29+
if (hash[leftChar] === 0) matched -= 1;
30+
hash[leftChar] += 1;
31+
}
32+
}
33+
}
34+
return min === Infinity ? '' : str.substring(subStringStart, subStringStart + min);
35+
};

0 commit comments

Comments
 (0)