-
Notifications
You must be signed in to change notification settings - Fork 0
/
1763.js
70 lines (66 loc) · 1.81 KB
/
1763.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
var longestNiceSubstring = function (s) {
this.maxPos = 0
this.maxLen = 0
let types = 0
for (let i = 0; i < s.length; ++i) {
types |= 1 << (s[i].toLowerCase().charCodeAt() - 'a'.charCodeAt())
}
types = bitCount(types)
for (let i = 1; i <= types; ++i) {
check(s, i)
}
return s.slice(maxPos, maxPos + maxLen)
}
const check = (s, typeNum) => {
const lowerCnt = new Array(26).fill(0)
const upperCnt = new Array(26).fill(0)
let cnt = 0
for (let l = 0, r = 0, total = 0; r < s.length; ++r) {
let idx = s[r].toLowerCase().charCodeAt() - 'a'.charCodeAt()
if ('a' <= s[r] && s[r] <= 'z') {
++lowerCnt[idx]
if (lowerCnt[idx] === 1 && upperCnt[idx] > 0) {
++cnt
}
} else {
++upperCnt[idx]
if (upperCnt[idx] === 1 && lowerCnt[idx] > 0) {
++cnt
}
}
total += (lowerCnt[idx] + upperCnt[idx]) === 1 ? 1 : 0
while (total > typeNum) {
idx = s[l].toLowerCase().charCodeAt() - 'a'.charCodeAt()
total -= (lowerCnt[idx] + upperCnt[idx]) === 1 ? 1 : 0
if ('a' <= s[l] && s[l] <= 'z') {
--lowerCnt[idx]
if (lowerCnt[idx] === 0 && upperCnt[idx] > 0) {
--cnt
}
} else {
--upperCnt[idx]
if (upperCnt[idx] === 0 && lowerCnt[idx] > 0) {
--cnt
}
}
++l
}
if (cnt === typeNum && r - l + 1 > maxLen) {
maxPos = l
maxLen = r - l + 1
}
}
}
var bitCount = function (n) {
let ret = 0
while (n) {
n &= n - 1
ret++
}
return ret
}
/*
2022/02/01
95 25
滑动窗口
*/