forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
count-vowel-substrings-of-a-string.py
65 lines (56 loc) · 1.68 KB
/
count-vowel-substrings-of-a-string.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
60
61
62
63
64
65
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def countVowelSubstrings(self, word):
"""
:type word: str
:rtype: int
"""
VOWELS = set("aeiou")
k = 5
def atLeastK(word, k):
cnt = collections.Counter()
result = left = right = 0
for i, c in enumerate(word):
if c not in VOWELS:
cnt = collections.Counter()
left = right = i+1
continue
cnt[c] += 1
while len(cnt) > k-1:
cnt[word[right]] -= 1
if not cnt[word[right]]:
del cnt[word[right]]
right += 1
result += right-left
return result
return atLeastK(word, k)
# Time: O(n)
# Space: O(1)
import collections
class Solution2(object):
def countVowelSubstrings(self, word):
"""
:type word: str
:rtype: int
"""
VOWELS = set("aeiou")
k = 5
def atMostK(word, k):
cnt = collections.Counter()
result = left = 0
for right, c in enumerate(word):
if c not in VOWELS:
cnt = collections.Counter()
left = right+1
continue
cnt[c] += 1
while len(cnt) > k:
cnt[word[left]] -=1
if not cnt[word[left]]:
del cnt[word[left]]
left += 1
result += right-left+1
return result
return atMostK(word, k) - atMostK(word, k-1)