[LeetCode] Count of Substrings Containing Every Vowel and K Consonants I

3305. Count of Substrings Containing Every Vowel and K Consonants I

You are given a string word and a non-negative integer k.

Return the total number of substrings of word that contain every vowel ('a', 'e', 'i', 'o', and 'u') at least once and exactly k consonants.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
long long countOfSubstrings(string word, int k) {
long long n = word.length(), res = 0;
unordered_set<char> vowels{'a','e','i','o','u'};
unordered_map<char,int> freq;
for(int i = 0, j = 0, cnt = 0; i < n; i++) {
while(j < n and (freq.size() != 5 or cnt < k)) {
if(vowels.count(word[j])) freq[word[j]]++;
else cnt++;
j++;
}
if(freq.size() == 5 and cnt == k) {
res += 1;
for(int k = j; k < word.length() and vowels.count(word[k]); k++) res++;
}
if(vowels.count(word[i])) {
if(--freq[word[i]] == 0) freq.erase(word[i]);
} else cnt--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/29/PS/LeetCode/count-of-substrings-containing-every-vowel-and-k-consonants-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.