class Solution(object):
def maxVowels(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
# 1.方法1也不知道对不对,在验证的时候超出时间限制了,
# 没有方法2好,方法1是每次都要计算滑动窗里中元音的个数
# n = len(s)
# if not s or n == 0:
# return 0
# i = 0
# j = k
# count = 0
# while j <= n:
# total = s[i:j]
# res = 0
# for t in total:
# if t in {'a', 'e', 'i', 'o', 'u'}:
# res += 1
# count = max(count, res)
# i += 1
# j += 1
# return count
# 2
n = len(s)
if not s or n == 0:
return 0
set_ = set(['a', 'e', 'i', 'o', 'u'])
res = 0
count = 0
# 先判断第一个k个字符串中的元音字母数
for i in s[:k]:
if i in set_:
count += 1
res = max(res, count)
# 滑动窗口开始往后滑
# 先判断排除的是否是元音,如果是-1
# 再判断新加的是否是元音,如果是+1
for i in range(k, n):
if s[i-k] in set_:
count -= 1
if s[i] in set_:
count += 1
res = max(res, count)
return res
70-滑动窗口--LC1456. 定长子串中元音的最大数目
最新推荐文章于 2024-05-28 20:47:24 发布