File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments