kt: add «3306. Count of Substrings Containing Every Vowel and K Consonants II»

URL:	https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-10 18:13:12 +01:00
parent 44a7d16cd9
commit 3f4a94d02a
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,45 @@
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)
}