LeetCode75-1456-Max-Number-of-Vowels

🧠 思路总结

只要题目是“求固定长度子串的某种属性的最大/最小值”,滑动窗口通常是最优解法。

先统计第一个长度为k的窗口元音数,然后滑动窗口。每次滑动向右移动一位,减去窗口左边的字符,如果左边字符是元音,那么count--;加上新进入窗口的右端字符,如果是元音,那么count++,更新maxCount。

❗ 易错点 / 小坑

不能直接简单判断如果左边不是元音,但是右边是元音count++

✅ 代码(Java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public int maxVowels(String s, int k) {
String v = "aeiou";
Set<Character> vSet = new HashSet<>();
for (int i = 0; i < v.length(); i++) {
vSet.add(v.charAt(i));
}
int count = 0;
for (int i = 0; i < k; i++) {
char c = s.charAt(i);
if (vSet.contains(c)){
count++;
}
}
int maxCount = count;
for (int i = k; i < s.length(); i++) {
char leftC = s.charAt(i - k);
char rightC = s.charAt(i);
if (vSet.contains(leftC)) {
count--;
}
if (vSet.contains(rightC)) {
count++;
}
maxCount = Math.max(count, maxCount);
}
return maxCount;
}
}

LeetCode75-1456-Max-Number-of-Vowels
https://powersixxx.github.io/leetcode-blog/2026/02/02/LeetCode75-1456-Max-Number-of-Vowels/
作者
Baowen Liu
发布于
2026年2月2日
许可协议