-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path395.js
47 lines (37 loc) · 827 Bytes
/
395.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
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
const longestSubstring = (s, k) => {
let maxStringLength = 0;
const iter = (s, k) => {
if (s.length === 0) {
return 0;
}
const charsCount = {};
const splitIdxs = [];
for (const char of s) {
charsCount[char] = (charsCount[char] || 0) + 1;
}
for (let i = 0; i < s.length; i += 1) {
if (charsCount[s[i]] < k) {
splitIdxs.push(i);
}
}
if (splitIdxs.length === 0) {
return s.length;
}
splitIdxs.push(s.length);
let left = 0;
splitIdxs.forEach((idx) => {
maxStringLength = Math.max(
maxStringLength,
longestSubstring(s.slice(left, idx), k),
);
left = idx + 1;
});
return maxStringLength;
};
return iter(s, k);
};