URL: https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/ Signed-off-by: Matej Focko <me@mfocko.xyz>
45 lines
1.2 KiB
Kotlin
45 lines
1.2 KiB
Kotlin
class Solution {
|
|
private fun isVowel(c: Char): Boolean = "aeiou".contains(c)
|
|
|
|
private fun atLeastK(
|
|
word: String,
|
|
k: Int,
|
|
): Long {
|
|
var substrings = 0L
|
|
var (start, end) = 0 to 0
|
|
|
|
val count = mutableMapOf<Char, Int>()
|
|
var consonants = 0
|
|
|
|
while (end < word.length) {
|
|
val newLetter = word[end]
|
|
|
|
when {
|
|
isVowel(newLetter) -> count[newLetter] = 1 + (count.getOrDefault(newLetter, 0))
|
|
else -> consonants++
|
|
}
|
|
|
|
while (count.size == 5 && consonants >= k) {
|
|
substrings += word.length - end
|
|
|
|
val startLetter = word[start]
|
|
when {
|
|
isVowel(startLetter) && count[startLetter] == 1 -> count.remove(startLetter)
|
|
isVowel(startLetter) -> count[startLetter] = count[startLetter]!! - 1
|
|
else -> consonants--
|
|
}
|
|
|
|
start++
|
|
}
|
|
|
|
end++
|
|
}
|
|
|
|
return substrings
|
|
}
|
|
|
|
fun countOfSubstrings(
|
|
word: String,
|
|
k: Int,
|
|
): Long = atLeastK(word, k) - atLeastK(word, k + 1)
|
|
}
|