1456. Maximum Number of Vowels in a Substring of Given Length
Description
Given a string s
and an integer k
, return the maximum number of vowel letters in any substring of s
with length k
.
Vowel letters in English are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
Example 1:
Input: s = "abciiidef", k = 3 Output: 3 Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2 Output: 2 Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3 Output: 2 Explanation: "lee", "eet" and "ode" contain 2 vowels.
Constraints:
1 <= s.length <= 105
s
consists of lowercase English letters.1 <= k <= s.length
Solutions
Solution: Sliding Window
- Time complexity: O(n)
- Space complexity: O(n)
JavaScript
js
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
const maxVowels = function (s, k) {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
let left = 0;
let result = (current = s
.slice(0, k)
.split('')
.filter(char => vowels.has(char)).length);
for (let index = k; index < s.length; index++) {
vowels.has(s[index]) && (current += 1);
vowels.has(s[left]) && (current -= 1);
left += 1;
result = Math.max(current, result);
}
return result;
};