Vowels of All Substrings
给一个字符串, 求所有子字符串的元音字母的和.
观察可以知道如果某一个字符是元音, 那么所有的包含这个元音的字符串的个数是它前边的所有字符的个数加上后边所有字符的个数.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public long countVowels(String word) { int n = word.length(); long count = 0; long res = 0; for(int i = 0; i < n; i++){ if(check(word.charAt(i))){ res += (count + 1) * (n - count); } count++; } return res; } private boolean check(char c) { return c == 'a' || c == 'e' || c == 'i' || c =='o' || c == 'u'; } } |