-
Notifications
You must be signed in to change notification settings - Fork 0
/
76.最小覆盖子串.js
70 lines (61 loc) · 1.31 KB
/
76.最小覆盖子串.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* @lc app=leetcode.cn id=76 lang=javascript
*
* [76] 最小覆盖子串
*/
// @lc code=start
/**
* @param {string} source
* @param {string} target
* @return {string}
*/
var minWindow = function(source, target) {
let windowObj = {},
needObj = {}
for (let i = 0; i < target.length; i++) {
const a = target[i]
// update needObj
if (needObj[a] == undefined) {
needObj[a] = 0
}
needObj[a]++
// update window
if (windowObj[a] == undefined) {
windowObj[a] = 0
}
}
let left = 0,
right = 0,
validNum = 0,
// case specific params: use start index and len to get minimum string
start = 0,
len = Infinity
while (right < source.length) {
const c = source[right]
right++
if (needObj[c]) {
windowObj[c]++
if (needObj[c] === windowObj[c]) {
validNum++
}
}
// shrink
while (validNum === Object.keys(needObj).length) {
if (right - left < len) {
start = left
len = right - left
}
const d = source[left]
left++
if (needObj[d]) {
if (needObj[d] === windowObj[d]) {
validNum--
}
windowObj[d]--
}
}
}
return len === Infinity ? '' : source.substring(start, start + len)
}
// @lc code=end
module.exports = { minWindow }