题目
解法1:stack
class Solution:def maxVowels(self, s: str, k: int) -> int:if len(s)<k:return 0candidates = ['a','e','i','o','u']ans = 0window = collections.deque()for c in s[:k]:if c in candidates:ans += 1window.append(c)p2 = kmax_ans = answhile p2<len(s):if s[p2] in candidates:ans += 1window.append(s[p2])left = window.popleft()if left in candidates:ans -= 1max_ans = max(max_ans,ans)#print(window)if max_ans == k:return kp2 += 1return max_ans
解法2:滑窗
实际上只需要管头尾两个元素进行相应的+1和-1就可以了,上面stack的pop操作直接通过计算index得到
class Solution:def maxVowels(self, s: str, k: int) -> int:candidates = ['a','e','i','o','u']arr = []for c in s:if c in candidates:arr.append(1)else:arr.append(0)count = 0for num in arr[:k]:if num == 1:count += 1 ans = countfor i in range(k,len(arr)):count = count + arr[i] - arr[i-k]ans = max(ans,count)if ans == k:return kreturn ans