此题采用简便算法,当字符串word中的word[i]是元音的时候,只需要计算word[i]出现在多少个子字符串中即可。
假设word[l,r]是包含word[i]的子字符串,word的长度为n,那么l需要满足0 <= l <= i, r需要满足i <= r <= n -1。
那么l有 i + 1 种情况,r有 n - i 种情况(情况数 = 右端点 - 左端点 + 1)。
那么包含word[i]的子字符串数量 = (i + 1)*(n - i)。
class Solution {
public:
long long countVowels(string word) {
long long res = 0;
string s = "aeiou";
int n = word.length();
for (int i = 0;i < n; i ++){
if (s.find(word[i]) != -1) //当find成功的时候,返回对应的下标,否则,返回一个特殊的int
res += (long long) (i + 1) * (long long)(n -i);
}
return res;
}
};