Given a string word
and a non-negative integer k
, return the total number of substrings of word
that satisfy both of the following conditions:
k
consonants.The task is to count all contiguous substrings of the input string word
that:
a
, e
, i
, o
, and u
.k
consonants (letters that are not vowels).5 <= word.length <= 2 * 10^5
word
consists only of lowercase English letters.0 <= k <= word.length - 5
word = "cuaeio"
, k = 1
"cuaeio"
. It contains all vowels (u
, a
, e
, i
, o
) and exactly 1 consonant (c
).1
word = "aeioubt"
, k = 2
"aeioubt"
has all vowels and exactly 2 consonants (b
and t
). No other substring meets the criteria.1
word = "abaeiou"
, k = 1
"baeiou"
(from index 1 to 6) contains vowels (a
, e
, i
, o
, u
) and 1 consonant (b
)."abaeiou"
(from index 0 to 6) also contains all vowels and exactly 1 consonant (b
).2
word
consists only of lowercase English letters.Loading component...
Loading component...
Main Function is not defined.
INPUT: word = "abaeiou", k = 1
OUTPUT: 2
public static long countOfSubstrings(String word, int k) {
int[][] frequencies = new int[2][128];
frequencies[0]['a'] = 1;
frequencies[0]['e'] = 1;
frequencies[0]['i'] = 1;
frequencies[0]['o'] = 1;
frequencies[0]['u'] = 1;
long response = 0;
int currentK = 0;
int vowels = 0;
int extraLeft = 0;
for (int right = 0, left = 0; right < word.length(); right++) {
char rightChar = word.charAt(right);
if (frequencies[0][rightChar] == 1) {
if (++frequencies[1][rightChar] == 1){
vowels++;
}//If End
}//If End
else{
currentK++;
}//Else End
while (currentK > k) {
char leftChar = word.charAt(left);
if (frequencies[0][leftChar] == 1) {
if (--frequencies[1][leftChar] == 0){
vowels--;
}//If End
}//If End
else {
currentK--;
}//Else End
left++;
extraLeft = 0;
}//Loop End
while (vowels == 5 && currentK == k && left < right && frequencies[0][word.charAt(left)] == 1 && frequencies[1][word.charAt(left)] > 1) {
extraLeft++;
frequencies[1][word.charAt(left)]--;
left++;
}//Loop End
if (currentK == k && vowels == 5) {
response += (1 + extraLeft);
}//If End
}//Loop End
return response;
}//function end
Utility Function is not required.