Table of Contents
一、中文版
二、英文版
三、My answer
四、解题报告
给你字符串 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
Given a string s
and an integer k
.
Return the maximum number of vowel letters in any substring of s
with length k
.
Vowel letters in English are (a, e, i, o, u).
Example 1:
Input: s = "abciiidef", k = 3 Output: 3 Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2 Output: 2 Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3 Output: 2 Explanation: "lee", "eet" and "ode" contain 2 vowels.
Example 4:
Input: s = "rhythms", k = 4 Output: 0 Explanation: We can see that s doesn't have any vowel letters.
Example 5:
Input: s = "tryhard", k = 4 Output: 1
Constraints:
1 <= s.length <= 10^5
s
consists of lowercase English letters.1 <= k <= s.length
class Solution:
def maxVowels(self, s: str, k: int) -> int:
# version 1: 硬遍历,超时
res = 0
vowel = ['a','e','i','o','u']
for i in range(len(s)-k+1):
tmp = 0
tmp_str = s[i:i+k]
for item in tmp_str:
if item in vowel:
tmp += 1
res = max(res, tmp)
return res
class Solution:
def maxVowels(self, s: str, k: int) -> int:
# version 2:滑动窗口
vowel = ['a','e','i','o','u']
i, j = 0, k
tmp_str = s[i:j]
base = 0
for item in tmp_str:
if item in vowel:
base += 1
res = base
for i in range(len(s)-k):
if s[i] in vowel:
base -= 1
if s[i+k] in vowel:
base += 1
res = max(res,base)
return res
数据结构:数据
算法:滑动窗口
实现:
1、version 1 直接遍历在数据量小时可行,但是看题目的限制( 1 <= s.length <= 10^5,
1 <= k <= s.length)可知,如果是两层 for 循环会超时。
2、滑动窗口,先求出前 k 个字符里面有几个元音,作为比较的 base,之后每次向右滑动时,左边扔掉一个字母,右边加入一个字母,每次都要判断扔掉和加入的字母是否是元音字母,在 base 的基础上加减即可。res 一直保存最大的元音字母数。