Input: word ="aba"Output: 6Explanation:
All possible substrings are:"a","ab","aba","b","ba", and "a".-"b" has 0 vowels in it
-"a","ab","ba", and "a" have 1 vowel each
-"aba" has 2 vowels in it
Hence, the total sum of vowels =0+1+1+1+1+2=6.
Input: word ="abc"Output: 3Explanation:
All possible substrings are:"a","ab","abc","b","bc", and "c".-"a","ab", and "abc" have 1 vowel each
-"b","bc", and "c" have 0 vowels each
Hence, the total sum of vowels =1+1+1+0+0+0=3.
Each vowel at position i appears in all substrings that start at or before i and end at or after i. The number of such substrings is (i+1) * (n-i) for a string of length n.
classSolution {
public:longlong countVowels(string word) {
longlong ans =0, n = word.size();
for (int i =0; i < n; ++i) {
char c = word[i];
if (c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u') {
ans += (longlong)(i +1) * (n - i);
}
}
return ans;
}
};
classSolution {
publiclongcountVowels(String word) {
long ans = 0, n = word.length();
for (int i = 0; i < n; i++) {
char c = word.charAt(i);
if (c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u') {
ans += (long)(i + 1) * (n - i);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funcountVowels(word: String): Long {
var ans = 0Lval n = word.length
for (i in word.indices) {
val c = word[i]
if (c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u') {
ans += (i + 1).toLong() * (n - i)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defcountVowels(self, word: str) -> int:
n = len(word)
vowels = set('aeiou')
ans =0for i, c in enumerate(word):
if c in vowels:
ans += (i +1) * (n - i)
return ans
1
2
3
4
5
6
7
8
9
10
pubfncount_vowels(word: &str) -> i64 {
let n = word.len() asi64;
letmut ans =0i64;
for (i, c) in word.chars().enumerate() {
ifmatches!(c, 'a'|'e'|'i'|'o'|'u') {
ans += (i asi64+1) * (n - i asi64);
}
}
ans
}