forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-beautiful-substrings-i.cpp
60 lines (56 loc) · 1.62 KB
/
count-beautiful-substrings-i.cpp
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
// Time: O(n + sqrt(k))
// Space: O(n)
// number theory, prefix sum, freq table
class Solution {
public:
int beautifulSubstrings(string s, int k) {
static const unordered_set<char> VOWELS = {'a', 'e', 'i', 'o', 'u'};
vector<int> prefix(size(s) + 1);
for (int i = 0; i < size(s); ++i) {
prefix[i + 1] = prefix[i] + (VOWELS.count(s[i]) ? +1 : -1);
}
int new_k = 1;
int x = k;
for (int i = 2; i * i <= k; ++i) {
int cnt = 0;
for (; x % i == 0; x /= i) {
++cnt;
}
if (cnt) {
new_k *= pow(i, (cnt + 1) / 2 + static_cast<int>(i == 2));
}
}
if (x != 1) {
new_k *= pow(x, (1 + 1) / 2 + static_cast<int>(x == 2));
}
unordered_map<int, unordered_map<int, int>> cnt;
int result = 0;
for (int i = 0; i < size(prefix); ++i) {
result += cnt[prefix[i]][i % new_k]++;
}
return result;
}
};
// Time: O(n^2)
// Space: O(1)
// brute force
class Solution2 {
public:
int beautifulSubstrings(string s, int k) {
static const unordered_set<char> VOWELS = {'a', 'e', 'i', 'o', 'u'};
int result = 0;
for (int i = 0; i < size(s); ++i) {
for (int j = i, c = 0, v = 0; j < size(s); ++j) {
if (VOWELS.count(s[j])) {
++v;
} else {
++c;
}
if (c == v && (c * v) % k == 0) {
++result;
}
}
}
return result;
}
};