Leetcode 刷题笔记 sliding window
滑动窗口(核心思想)
- 滑动窗口适合子数组的搜索
- 同向双指针检索数组,通过start 和 end 指针定位滑动窗口
思想:滑动 end 指针 将s[end] 加入窗口,满足要求后移出s[start] 并将start 指针前移 进行窗口的滑动。
209. Minimum Size Subarray Sum (medium)
https://leetcode.com/problems/minimum-size-subarray-sum/
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
start = 0
end = 0
total = 0
rst = float('inf')
for end in range (len(nums)):
total += nums[end]
while total >= target:
rst = min(rst, end - start + 1)
total -= nums[start]
start += 1
if rst != float('inf'):
return rst
return 0
76. Minimum Window Substring (hard)
https://leetcode.com/problems/minimum-window-substring/
class Solution:
def minWindow(self, s: str, t: str) -> str:
from collections import Counter
end = 0
window = {}
tmp_dict = Counter(t)
for key in tmp_dict:
if key not in window:
window[key] = 0
start = 0
rst = ''
def countain(window, tmp):
for key in tmp:
if window[key] < tmp[key]:
return False
return True
min_val = float('inf')
for end in range(len(s)):
if s[end] in t:
window[s[end]] += 1
while countain(window, tmp_dict):
if min_val > end - start + 1:
min_val = end - start + 1
rst = s[start:end + 1]
if s[start] in window:
window[s[start]] -= 1
start += 1
return rst
- 通过计数判断是否满足条件
1456. Maximum Number of Vowels in a Substring of Given Length (medium)
https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowel = 'aeiou'
# first window
rst = 0
for i in range(k):
if s[i] in vowel:
rst += 1
tmp_cnt = rst # first window
for i in range(k, len(s)):
if s[i-k] in vowel:
tmp_cnt -= 1
if s[i] in vowel:
tmp_cnt += 1
rst = max(rst, tmp_cnt)
return rst
本文介绍了如何利用滑动窗口技巧解决LeetCode中的三个经典问题:最小子数组和、最小窗口子串匹配和最长元音字符子串。通过实例解析核心思想并提供Python代码实现,帮助理解在查找子数组和、字符串匹配和字符计数场景中的高效算法。
701

被折叠的 条评论
为什么被折叠?



