-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path127.py
More file actions
56 lines (49 loc) · 2.02 KB
/
127.py
File metadata and controls
56 lines (49 loc) · 2.02 KB
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
class Solution:
def _isVowel(self, c: str) -> bool:
return c == "a" or c == "e" or c == "i" or c == "o" or c == "u"
def countOfSubstrings(self, word: str, k: int) -> int:
num_valid_substrings = 0
start = end = 0
vowel_count = {} # Dictionary to keep counts of vowels
consonant_count = 0 # Count of consonants
next_consonant = [0] * len(
word
) # Array to compute index of next consonant for all indices
next_consonant_index = len(word)
for i in range(len(word) - 1, -1, -1):
next_consonant[i] = next_consonant_index
if not self._isVowel(word[i]):
next_consonant_index = i
while end < len(word):
new_letter = word[end]
if self._isVowel(new_letter):
vowel_count[new_letter] = vowel_count.get(new_letter, 0) + 1
else:
consonant_count += 1
while (
consonant_count > k
): # Shrink window if too many consonants are present
start_letter = word[start]
if self._isVowel(start_letter):
vowel_count[start_letter] -= 1
if vowel_count[start_letter] == 0:
del vowel_count[start_letter]
else:
consonant_count -= 1
start += 1
while (
start < len(word)
and len(vowel_count) == 5
and consonant_count == k
): # Try to shrink if window is valid
num_valid_substrings += next_consonant[end] - end
start_letter = word[start]
if self._isVowel(start_letter):
vowel_count[start_letter] -= 1
if vowel_count[start_letter] == 0:
del vowel_count[start_letter]
else:
consonant_count -= 1
start += 1
end += 1
return num_valid_substrings