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:
parent
44a7d16cd9
commit
3f4a94d02a
1 changed files with 45 additions and 0 deletions
|
@ -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)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue