Count Vowel Substrings of a String Problem
#2062
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2062.
A substring is a contiguous (non-empty) sequence of characters within a string.
A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.
Given a string word, return the number of vowel substrings in word.
Example 1:
Input: word = "aeiouu"
Output: 2
Explanation: The vowel substrings of word are as follows (underlined):
- "aeiouu"
- "aeiouu"
Example 2:
Input: word = "unicornarihan"
Output: 0
Explanation: Not all 5 vowels are present, so there are no vowel substrings.
Example 3:
Input: word = "cuaieuouac"
Output: 7
Explanation: The vowel substrings of word are as follows (underlined):
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
Constraints:
1 <= word.length <= 100wordconsists of lowercase English letters only.
Solution
Approach: Brute Force Enumeration + Hash Table
Fix the left end i of the substring and extend the right end j one character at a time, keeping a set of the vowels seen so far. If the character at j is not a vowel, stop: no longer substring from i can qualify. Otherwise add it to the set, and whenever the set holds all 5 vowels, count one more vowel substring.
Complexity: time O(n^2), space O(C) with C = 5, where n is the length of word.
class Solution:
def countVowelSubstrings(self, word: str) -> int:
s = set("aeiou")
ans, n = 0, len(word)
for i in range(n):
t = set()
for c in word[i:]:
if c not in s:
break
t.add(c)
ans += len(t) == 5
return ans