[LeetCode] Vowels of All Substrings

2063. Vowels of All Substrings

Given a string word, return the sum of the number of vowels (‘a’, ‘e’, ‘i’, ‘o’, and ‘u’) in every substring of word.

A substring is a contiguous (non-empty) sequence of characters within a string.

Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
long long countVowels(string word) {
long long res = 0, n = word.size();
unordered_set<char> vowel = {'a','e','i','o','u'};
for(int i = 0; i < n; i++) {
if(vowel.count(word[i])) res += (i + 1) * (n - i);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/09/PS/LeetCode/vowels-of-all-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.