-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
count-beautiful-substrings-i.py
59 lines (55 loc) · 1.45 KB
/
count-beautiful-substrings-i.py
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
# Time: O(n + sqrt(k))
# Space: O(n)
# number theory, prefix sum, freq table
class Solution(object):
def beautifulSubstrings(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
VOWELS = set("aeiou")
prefix = [0]*(len(s)+1)
for i in xrange(len(s)):
prefix[i+1] = prefix[i]+(+1 if s[i] in VOWELS else -1)
new_k = 1
x = k
for i in xrange(2, k+1):
if i*i > k:
break
cnt = 0
while x%i == 0:
x //= i
cnt += 1
if cnt:
new_k *= i**((cnt+1)//2+int(i == 2))
if x != 1:
new_k *= x**((1+1)//2+int(x == 2))
cnt = collections.Counter()
result = 0
for i, p in enumerate(prefix):
result += cnt[p, i%new_k]
cnt[p, i%new_k] += 1
return result
# Time: O(n^2)
# Space: O(1)
# brute force
class Solution2(object):
def beautifulSubstrings(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
VOWELS = set("aeiou")
result = 0
for i in xrange(len(s)):
c = v = 0
for j in xrange(i, len(s)):
if s[j] in VOWELS:
v += 1
else:
c += 1
if c == v and (c*v)%k == 0:
result += 1
return result