Input: word ="cuaieuouac"Output: 7Explanation: The vowel substrings of word are as follows(underlined):-"c** _uaieuo_** uac"-"c** _uaieuou_** ac"-"c** _uaieuoua_** c"-"cu** _aieuo_** uac"-"cu** _aieuou_** ac"-"cu** _aieuoua_** c"-"cua** _ieuoua_** c"
A substring is a vowel substring if it contains only vowels and all five vowels at least once. We can use a sliding window to check all substrings that consist only of vowels and count those that contain all five vowels.
classSolution {
public:int countVowelSubstrings(string word) {
int n = word.size(), ans =0;
auto isVowel = [](char c) {
return c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u';
};
for (int i =0; i < n; ++i) {
set<char> st;
for (int j = i; j < n && isVowel(word[j]); ++j) {
st.insert(word[j]);
if (st.size() ==5) ++ans;
}
}
return ans;
}
};
classSolution {
publicintcountVowelSubstrings(String word) {
int n = word.length(), ans = 0;
for (int i = 0; i < n; i++) {
Set<Character> st =new HashSet<>();
for (int j = i; j < n && isVowel(word.charAt(j)); j++) {
st.add(word.charAt(j));
if (st.size() == 5) ans++;
}
}
return ans;
}
privatebooleanisVowel(char c) {
return c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funcountVowelSubstrings(word: String): Int {
val n = word.length
var ans = 0funisVowel(c: Char) = c in"aeiou"for (i in0 until n) {
val st = mutableSetOf<Char>()
for (j in i until n) {
if (!isVowel(word[j])) break st.add(word[j])
if (st.size ==5) ans++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defcountVowelSubstrings(self, word: str) -> int:
vowels = {'a','e','i','o','u'}
n = len(word)
ans =0for i in range(n):
st = set()
for j in range(i, n):
if word[j] notin vowels:
break st.add(word[j])
if len(st) ==5:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfncount_vowel_substrings(word: String) -> i32 {
let n = word.len();
let w = word.as_bytes();
let vowels = [b'a', b'e', b'i', b'o', b'u'];
letmut ans =0;
for i in0..n {
letmut st = std::collections::HashSet::new();
for j in i..n {
if!vowels.contains(&w[j]) { break; }
st.insert(w[j]);
if st.len() ==5 { ans +=1; }
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
countVowelSubstrings(word: string):number {
constvowels=newSet(['a','e','i','o','u'])
letans=0for (leti=0; i<word.length; ++i) {
constst=newSet<string>()
for (letj=i; j<word.length; ++j) {
if (!vowels.has(word[j])) breakst.add(word[j])
if (st.size===5) ans++ }
}
returnans }
}