leetcode-190周赛-1456-定长子串中元音的最大数目
提交:
class Solution: def maxVowels(self, s: str, k: int) -> int: n = len(s) dp = [0] * (n + 1) for i in range(n): if s[i] in "aeiou": dp[i + 1] = dp[i] + 1 else: dp[i + 1] = dp[i] if k >= n: return dp[-1] res = 0 for i in range(k-1,n): res = max(res,dp[i+1] - dp[i-k+1]) return res
优化:
class Solution: def maxVowels(self, s: str, k: int) -> int: r = h = 0 vowel = set('aeiou') for i, c in enumerate(s): if c in vowel: h += 1 if i >= k and s[i-k] in vowel: h -= 1 r = max(r, h) return r