Skip to content

Commit 9cb24d6

Browse files
authored
Update 2949-count-beautiful-substrings-ii.js
1 parent 2b9a89b commit 9cb24d6

File tree

1 file changed

+62
-16
lines changed

1 file changed

+62
-16
lines changed

2949-count-beautiful-substrings-ii.js

Lines changed: 62 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,73 @@
1+
const set = new Set(['a', 'e', 'i', 'o', 'u']);
12
/**
23
* @param {string} s
34
* @param {number} k
45
* @return {number}
56
*/
67
var beautifulSubstrings = function(s, k) {
7-
let ans = 0, cur = 0;
8-
let mp = new Map();
9-
mp.set(0, [-1]);
10-
for (let i = 0; i < s.length; i++) {
11-
let ch = s[i];
12-
if (ch === 'a' || ch === 'e' || ch === 'i' || ch === 'o' || ch === 'u') {
13-
cur++;
8+
const primes = Eratosthenes(k);
9+
let m = 1;
10+
11+
for (const p of primes) {
12+
let count = 0;
13+
while (k % p === 0) {
14+
count++;
15+
k /= p;
16+
}
17+
if (count !== 0 && count % 2 === 1) {
18+
m *= Math.pow(p, (count + 1) / 2);
19+
} else if (count !== 0 && count % 2 === 0) {
20+
m *= Math.pow(p, count / 2);
21+
}
22+
}
23+
m *= 2;
24+
25+
const n = s.length;
26+
s = '#' + s; // Prepend a character to ensure 1-based indexing
27+
let ret = 0;
28+
29+
const map = new Map();
30+
map.set(0, new Map());
31+
map.get(0).set(0, 1);
32+
33+
let count = 0;
34+
35+
for (let i = 1; i <= n; i++) {
36+
if (set.has(s[i])) {
37+
count++;
1438
} else {
15-
cur--;
39+
count--;
40+
}
41+
42+
if (map.has(count) && map.get(count).has(i % m)) {
43+
ret += map.get(count).get(i % m);
1644
}
17-
for (let x of (mp.get(cur) || []) ) {
18-
let d = (i - x) / 2;
19-
if (Math.pow(d, 2) % k === 0) {
20-
ans++;
21-
}
45+
46+
if (!map.has(count)) {
47+
map.set(count, new Map());
2248
}
23-
if (!mp.has(cur)) mp.set(cur, []);
24-
mp.get(cur).push(i);
49+
map.get(count).set(i % m, (map.get(count).get(i % m) || 0) + 1);
2550
}
26-
return ans;
51+
52+
return ret;
2753
};
54+
55+
function Eratosthenes(n) {
56+
const q = Array(n + 1).fill(0);
57+
const primes = [];
58+
59+
for (let i = 2; i <= Math.sqrt(n); i++) {
60+
if (q[i] === 1) continue;
61+
for (let j = i * 2; j <= n; j += i) {
62+
q[j] = 1;
63+
}
64+
}
65+
66+
for (let i = 2; i <= n; i++) {
67+
if (q[i] === 0) {
68+
primes.push(i);
69+
}
70+
}
71+
72+
return primes;
73+
}

0 commit comments

Comments
 (0)