Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9406a4b

Browse files
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)

AltStyle によって変換されたページ (->オリジナル) /