定长子串中元音的最大数目
LeetCode1456-定长子串中元音的最大数目(滑动窗口)
#resource / algorithm
#type / snippet
#status / evergreen
#source / leetcode
#algo / sliding-window
[!info] related notes 算法面试题型 MOC 滑动窗口
定长子串中元音的最大数目
1456. 定长子串中元音的最大数目 - 力扣(LeetCode)
题目
[1456. 定长子串中元音的最大数目](https://leetcode.cn/problems/maximum-number-of-vowels-in-a-substring-of-given-length/)
已解答
中等
相关标签
相关企业
提示
给你字符串 `s` 和整数 `k` 。
请返回字符串 `s` 中长度为 `k` 的单个子字符串中可能包含的最大元音字母数。
英文中的 **元音字母** 为(`a`, `e`, `i`, `o`, `u`)。
**示例 1:**
**输入:**s = "abciiidef", k = 3
**输出:**3
**解释:**子字符串 "iii" 包含 3 个元音字母。
**示例 2:**
**输入:**s = "aeiou", k = 2
**输出:**2
**解释:**任意长度为 2 的子字符串都包含 2 个元音字母。
**示例 3:**
**输入:**s = "leetcode", k = 3
**输出:**2
**解释:**"lee"、"eet" 和 "ode" 都包含 2 个元音字母。
**示例 4:**
**输入:**s = "rhythms", k = 4
**输出:**0
**解释:**字符串 s 中不含任何元音字母。
**示例 5:**
**输入:**s = "tryhard", k = 4
**输出:**1
**提示:**
- `1 <= s.length <= 10^5`
- `s` 由小写英文字母组成
- `1 <= k <= s.length`
题解
定长滑动窗口
var maxVowels = function(s, k) {
let map = new Map([
['a', true],
['e', true],
['i', true],
['o', true],
['u', true]
]);
let leftInx = 0;
let max = 0,result = 0;
for (let i = 0; i < s.length; i++) {
if (map.has(s[i])) {
max++;
}
if (i - leftInx < k - 1) continue;
result = Math.max(max, result);
if (map.has(s[leftInx])) {
max--
}
leftInx++;
}
return result;
};