LeetCode in Kotlin

2063. Vowels of All Substrings

Medium

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.

Example 1:

Input: word = “aba”

Output: 6

Explanation: All possible substrings are: “a”, “ab”, “aba”, “b”, “ba”, and “a”.

Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6.

Example 2:

Input: word = “abc”

Output: 3

Explanation: All possible substrings are: “a”, “ab”, “abc”, “b”, “bc”, and “c”.

Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.

Example 3:

Input: word = “ltcd”

Output: 0

Explanation: There are no vowels in any substring of “ltcd”.

Constraints:

Solution

class Solution {
    fun countVowels(word: String): Long {
        var ans: Long = 0
        for (i in word.indices) {
            if (isVowel(word[i])) {
                val right = word.length - i.toLong() - 1
                ans += (i.toLong() + 1) * (right + 1)
            }
        }
        return ans
    }

    private fun isVowel(ch: Char): Boolean {
        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'
    }
}