|
| 1 | +/// https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii |
| 2 | +/// You are given a string word and a non-negative integer k. |
| 3 | +/// |
| 4 | +/// Return the total number of substrings of word that contain every vowel ('a', 'e', 'i', /'o', and 'u') at least once and exactly k consonants. |
| 5 | +/// |
| 6 | +/// |
| 7 | +/// |
| 8 | +/// Example 1: |
| 9 | +/// |
| 10 | +/// Input: word = "aeioqq", k = 1 |
| 11 | +/// |
| 12 | +/// Output: 0 |
| 13 | +/// |
| 14 | +/// Explanation: |
| 15 | +/// |
| 16 | +/// There is no substring with every vowel. |
| 17 | +/// |
| 18 | +/// Example 2: |
| 19 | +/// |
| 20 | +/// Input: word = "aeiou", k = 0 |
| 21 | +/// |
| 22 | +/// Output: 1 |
| 23 | +/// |
| 24 | +/// Explanation: |
| 25 | +/// |
| 26 | +/// The only substring with every vowel and zero consonants is word[0..4], which is "aeiou". |
| 27 | +/// |
| 28 | +/// Example 3: |
| 29 | +/// |
| 30 | +/// Input: word = "ieaouqqieaouqq", k = 1 |
| 31 | +/// |
| 32 | +/// Output: 3 |
| 33 | +/// |
| 34 | +/// Explanation: |
| 35 | +/// |
| 36 | +/// The substrings with every vowel and one consonant are: |
| 37 | +/// |
| 38 | +/// word[0..5], which is "ieaouq". |
| 39 | +/// word[6..11], which is "qieaou". |
| 40 | +/// word[7..12], which is "ieaouq". |
| 41 | +class Daily20250310 { |
| 42 | + int countOfSubstrings(String word, int k) { |
| 43 | + return substrings(word, k) - substrings(word, k - 1); |
| 44 | + } |
| 45 | + |
| 46 | + int substrings(String word, int k) { |
| 47 | + if (k == -1) return 0; |
| 48 | + int res = 0, uniqueVowels = 0, vowels = 0; |
| 49 | + Map<String, int> vowelLastSeen = {}; |
| 50 | + |
| 51 | + for (int l = 0, r = 0; r < word.length; r++) { |
| 52 | + if (isVowel(word[r])) { |
| 53 | + vowels++; |
| 54 | + if (!vowelLastSeen.containsKey(word[r]) || |
| 55 | + vowelLastSeen[word[r]]! < l) { |
| 56 | + uniqueVowels++; |
| 57 | + } |
| 58 | + vowelLastSeen[word[r]] = r; |
| 59 | + } |
| 60 | + |
| 61 | + while (r - l + 1 - vowels > k) { |
| 62 | + if (isVowel(word[l])) { |
| 63 | + vowels--; |
| 64 | + if (vowelLastSeen[word[l]] == l) { |
| 65 | + uniqueVowels--; |
| 66 | + } |
| 67 | + } |
| 68 | + l++; |
| 69 | + } |
| 70 | + |
| 71 | + if (uniqueVowels == 5) { |
| 72 | + final minVowelLastSeen = |
| 73 | + vowelLastSeen.values.toList().reduce((value, element) { |
| 74 | + if (value < element) return value; |
| 75 | + return element; |
| 76 | + }); |
| 77 | + res += minVowelLastSeen - l + 1; |
| 78 | + } |
| 79 | + } |
| 80 | + return res; |
| 81 | + } |
| 82 | + |
| 83 | + bool isVowel(String letter) { |
| 84 | + return "aeiou".contains(letter); |
| 85 | + } |
| 86 | +} |
0 commit comments