|
| 1 | +// https://leetcode.com/problems/count-vowel-substrings-of-a-string |
| 2 | +// T: O(|word|) |
| 3 | +// S: O(|word|) |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Set; |
| 8 | + |
| 9 | +public class CountVowelSubstringsOfAString { |
| 10 | + private static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o','u'); |
| 11 | + |
| 12 | + public static int countVowelSubstrings(String word) { |
| 13 | + int vowelSubstrings = 0; |
| 14 | + final Map<Character, Integer> vowels = new HashMap<>(); |
| 15 | + for (int j = 0 ; j < word.length() ; j++) { |
| 16 | + if (isVowel(word.charAt(j))) { |
| 17 | + addToMap(vowels, word.charAt(j)); |
| 18 | + for (int i = j + 1, k = j ; i < word.length() ; i++) { |
| 19 | + if (isVowel(word.charAt(i))) { |
| 20 | + addToMap(vowels, word.charAt(i)); |
| 21 | + for ( ; k < i && vowels.size() == 5 ; k++) { |
| 22 | + removeFromMap(vowels, word.charAt(k)); |
| 23 | + } |
| 24 | + vowelSubstrings += k - j; |
| 25 | + if (i == word.length() - 1) { |
| 26 | + j = i; |
| 27 | + } |
| 28 | + } else { |
| 29 | + j = i; |
| 30 | + vowels.clear(); |
| 31 | + break; |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + return vowelSubstrings; |
| 37 | + } |
| 38 | + |
| 39 | + private static boolean isVowel(char c) { |
| 40 | + return VOWELS.contains(c); |
| 41 | + } |
| 42 | + |
| 43 | + private static void addToMap(Map<Character, Integer> frequencies, char c) { |
| 44 | + frequencies.put(c, frequencies.getOrDefault(c, 0) + 1); |
| 45 | + } |
| 46 | + |
| 47 | + private static void removeFromMap(Map<Character, Integer> frequencies, char c) { |
| 48 | + if (frequencies.getOrDefault(c, 0) == 1) frequencies.remove(c); |
| 49 | + else frequencies.put(c, frequencies.get(c) - 1); |
| 50 | + } |
| 51 | +} |
0 commit comments