forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhsskey.js
More file actions
55 lines (41 loc) · 1.36 KB
/
hsskey.js
File metadata and controls
55 lines (41 loc) · 1.36 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
55
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
if (s.length === 0 || t.length === 0) return "";
const dictT = {};
for (let char of t) {
dictT[char] = (dictT[char] || 0) + 1;
}
const required = Object.keys(dictT).length;
let formed = 0;
const windowCounts = {};
let left = 0, right = 0;
let minLen = Infinity;
let minLeft = 0, minRight = 0;
while (right < s.length) {
const character = s[right];
windowCounts[character] = (windowCounts[character] || 0) + 1;
if (dictT[character] && windowCounts[character] === dictT[character]) {
formed++;
}
while (left <= right && formed === required) {
const currentLen = right - left + 1;
if (currentLen < minLen) {
minLen = currentLen;
minLeft = left;
minRight = right;
}
const leftChar = s[left];
windowCounts[leftChar]--;
if (dictT[leftChar] && windowCounts[leftChar] < dictT[leftChar]) {
formed--;
}
left++;
}
right++;
}
return minLen === Infinity ? "" : s.substring(minLeft, minRight + 1);
};