Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9406a4b

Browse files
committed
2947. Count Beautiful Substrings I
1 parent 4ccbde3 commit 9406a4b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2947. Count Beautiful Substrings I
5+
6+
// Time complexity: O(n+k)
7+
// Space complexity: O(n)
8+
9+
func beautifulSubstrings(_ s: String, _ k: Int) -> Int {
10+
var grps = [Int: [Int]]()
11+
grps[0] = [0]
12+
13+
let vowels: Set<Character> = Set("aeiou")
14+
var presum = 0
15+
16+
for (i, char) in s.enumerated() {
17+
if vowels.contains(char) {
18+
presum += 1
19+
} else {
20+
presum -= 1
21+
}
22+
grps[presum, default: []].append(i + 1)
23+
}
24+
25+
var x = 1
26+
while x <= k && x * x % k != 0 {
27+
x += 1
28+
}
29+
x *= 2
30+
31+
var ans: Int64 = 0
32+
for (_, grp) in grps {
33+
var mod = [Int](repeating: 0, count: x)
34+
for i in grp {
35+
ans += Int64(mod[i % x])
36+
mod[i % x] += 1
37+
}
38+
}
39+
return Int(ans)
40+
}
41+
}

0 commit comments

Comments
 (0)