LeetCode 题解工作台

定长子串中元音的最大数目

给你字符串 s 和整数 k 。 请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。 英文中的 元音字母 为( a , e , i , o , u )。 示例 1: 输入: s = "abciiidef", k = 3 输出: 3 解释: 子字符串 "iii" 包含 3 个元音…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们首先统计前 个字符中元音字母的个数,记为 ,初始化答案 为 。 然后我们从 开始遍历字符串,每次遍历时,我们将当前字符加入窗口,如果当前字符是元音字母,则 加一;将窗口第一个字符移出窗口,如果移除的字符是元音字母,则 减一。然后,我们更新答案 $ans = \max(ans, cnt)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你字符串 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
lightbulb

解题思路

方法一:滑动窗口

我们首先统计前 kk 个字符中元音字母的个数,记为 cntcnt,初始化答案 ansanscntcnt

然后我们从 kk 开始遍历字符串,每次遍历时,我们将当前字符加入窗口,如果当前字符是元音字母,则 cntcnt 加一;将窗口第一个字符移出窗口,如果移除的字符是元音字母,则 cntcnt 减一。然后,我们更新答案 ans=max(ans,cnt)ans = \max(ans, cnt)

遍历结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = set("aeiou")
        ans = cnt = sum(c in vowels for c in s[:k])
        for i in range(k, len(s)):
            cnt += int(s[i] in vowels) - int(s[i - k] in vowels)
            ans = max(ans, cnt)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates a strong understanding of the sliding window technique.

  • question_mark

    The candidate optimizes the solution with a constant space complexity.

  • question_mark

    The candidate handles edge cases effectively.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the problem by trying to find a solution without using a sliding window.

  • error

    Failing to maintain the correct vowel count during the sliding window update step.

  • error

    Not considering edge cases such as no vowels or all vowels in the string.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the window size k can change dynamically?

  • arrow_right_alt

    Can the problem be solved with a brute force approach, and if so, how does it compare to the sliding window method?

  • arrow_right_alt

    How would this solution change if we needed to track the substring with the maximum vowel count, not just the count itself?

help

常见问题

外企场景

定长子串中元音的最大数目题解:滑动窗口(状态滚动更新) | LeetCode #1456 中等