Skip to content

定长滑动窗口

题目示例:定长滑动窗口最大元音字母数

java
class Solution {
    public int maxVowels(String s, int k) {
        char[] c = s.toCharArray();
        int target = 0;
        Set<Character> Vowels = Set.of('a', 'e', 'i', 'o', 'u');
        for (int i = 0; i < k; i++) {
            if (Vowels.contains(c[i])) target++;
        }
        int res = target;
        for (int i = k; i < c.length; i++) {
            if (Vowels.contains(c[i])) target++;
            if (Vowels.contains(c[i - k])) target--;
            res = Math.max(res, target);
        }
        return res;
    }
}

核心思路

  1. 初始化窗口:先统计前 k 个元素的元音数。
  2. 滑动窗口:从 k 开始遍历,每次向右移动一位,增加新进入的元素,减去离开窗口的元素。
  3. 更新结果:每次移动后记录最大值。

贡献者

The avatar of contributor named as 四季夏目 四季夏目
The avatar of contributor named as Claude Opus 4.5 Claude Opus 4.5

页面历史

最近更新

基于 VitePress 搭建