-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path076.js
More file actions
57 lines (51 loc) · 1.48 KB
/
076.js
File metadata and controls
57 lines (51 loc) · 1.48 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
56
57
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
if (t.length === 0) return "";
let targetMap = {};
for(let i = 0; i < t.length; ++i) {
targetMap[t[i]] = targetMap[t[i]] ? targetMap[t[i]] + 1 : 1;
}
// try find first match
let currentMap = {};
let targetCount = t.length;
let end = 0;
while(targetCount > 0 && end <= s.length) {
const currentChar = s[end];
if (targetMap[currentChar]) {
currentMap[currentChar] = currentMap[currentChar] ? currentMap[currentChar] + 1 : 1;
if (currentMap[currentChar] <= targetMap[currentChar]) --targetCount;
}
++end;
}
if (targetCount > 0) return "";
let start = 0;
let minLength = end - start;
let resultStart = start;
let resultEnd = end;
while(end <= s.length) {
// move start if s[start] not in targetMap or it's current count is larger then target count
while(!(s[start] in targetMap) || currentMap[s[start]] > targetMap[s[start]]) {
if (s[start] in targetMap) {
currentMap[s[start]] = currentMap[s[start]] - 1;
}
++start;
const currentLength = end - start;
if (currentLength < minLength) {
minLength = currentLength;
resultStart = start;
resultEnd = end;
}
}
while(!(s[end] in targetMap) && end < s.length) {
++end;
}
if (end === t.length) break;
currentMap[s[end]] = currentMap[s[end]] + 1;
++end;
}
return s.substr(resultStart, minLength);
};