日野弥生:勉強しよう

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

发表于2025年04月21日

#字符串 #滑动窗口

先求滑动窗口的最大值,然后滑动过程中不断减去开头和附加末尾,循环体循环一次求一次最大值。总体时间复杂度是O(n)。注意提前剪枝。

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        def isVowel(ch: str) -> bool:
            return ch in "aeiou"
        head, tail = 0, k
        maximum = 0
        currCnt = 0
        for ch in range(head, tail):
            if isVowel(s[ch]):
                currCnt += 1
        maximum = currCnt
        # 提前剪枝
        if maximum == k:
            return k

        while tail < len(s):
            if isVowel(s[head]):
                currCnt -= 1
            if isVowel(s[tail]):
                currCnt += 1
            maximum = max(maximum, currCnt)
            tail += 1
            head += 1
            # 提前剪枝
            if maximum == k:
                return k
        return maximum
            

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/maximum-number-of-vowels-in-a-substring-of-given-length/

上一篇

LeetCode 643 - 子数组最大平均数 I

下一篇

LeetCode 1732 - 找到最高海拔