Leetcode 2062. Count Vowel Substrings of a String
You are given a string word
. A vowel substring is a substring of word
that consists only of vowels (a
, e
, i
, o
, u
) and has all five vowels present at least once.
Your task is to return the number of vowel substrings in the given word.
Input: word = "aeiouu"
Output: 2
Input: word = "unicornarihan"
Output: 0
Input: word = "cuaieuouac"
Output: 7
1 <= word.length <= 100
word
consists only of lowercase English letters.y
considered a vowel in this context?
a
, e
, i
, o
, u
are considered vowels.To solve this problem, we can use a sliding window approach:
We will accomplish this in a nested loop to check all substrings and use a set to check the presence of vowels.
import java.util.*;
public class Solution {
public int countVowelSubstrings(String word) {
Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
int count = 0;
for (int i = 0; i < word.length(); i++) {
Set<Character> seen = new HashSet<>();
for (int j = i; j < word.length(); j++) {
char ch = word.charAt(j);
if (!vowels.contains(ch)) {
break;
}
seen.add(ch);
if (seen.size() == 5) {
count++;
}
}
}
return count;
}
}
The time complexity of this solution is O(n^2), where n
is the length of the input string:
n
times, iterating through each character in the string.n
times for each character in the string.The space complexity is O(1) since we are using a fixed size set to keep track of vowels seen in the current substring.
This algorithm effectively checks each possible substring in a nested manner and ensures that all conditions for a valid vowel substring are met. The constraints (word length up to 100) make the O(n^2) approach feasible.
This concludes the solution to the “Count Vowel Substrings of a String” problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?