Vowels of All Substrings

medium math string dp contribution

Problem

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

Inputword = "aba"
Output6
'a' at 0 → 1·3 = 3, 'a' at 2 → 3·1 = 3, total = 6.

def count_vowels(word):
    n = len(word)
    total = 0
    for i, c in enumerate(word):
        if c in 'aeiou':
            total += (i + 1) * (n - i)
    return total
function countVowels(word) {
  const n = word.length;
  let total = 0n;
  for (let i = 0; i < n; i++) {
    if ("aeiou".includes(word[i])) {
      total += BigInt(i + 1) * BigInt(n - i);
    }
  }
  return total;
}
class Solution {
    public long countVowels(String word) {
        int n = word.length();
        long total = 0;
        for (int i = 0; i < n; i++) {
            char c = word.charAt(i);
            if ("aeiou".indexOf(c) >= 0) {
                total += (long)(i + 1) * (n - i);
            }
        }
        return total;
    }
}
long long countVowels(string word) {
    int n = word.size();
    long long total = 0;
    for (int i = 0; i < n; i++) {
        if (string("aeiou").find(word[i]) != string::npos) {
            total += (long long)(i + 1) * (n - i);
        }
    }
    return total;
}
Time: O(n) Space: O(1)