LeetCode Entry
1456. Maximum Number of Vowels in a Substring of Given Length
we can use Set to check if it is a vowel
1456. Maximum Number of Vowels in a Substring of Given Length medium
fun maxVowels(s: String, k: Int): Int {
val vowels = setOf('a', 'e', 'i', 'o', 'u')
var count = 0
var max = 0
for (i in 0..s.lastIndex) {
if (s[i] in vowels) count++
if (i >= k && s[i - k] in vowels) count--
if (count > max) max = count
}
return max
}
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/203
Intuition
Count vowels, increasing them on the right border and decreasing on the left of the sliding window.
Approach
- we can use
Setto check if it is a vowel - look at
a[i - k]to detect if we must start move left border fromi == kComplexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(1)\)