Leetcode 刷题笔记 (sliding window)

本文介绍了如何利用滑动窗口技巧解决LeetCode中的三个经典问题:最小子数组和、最小窗口子串匹配和最长元音字符子串。通过实例解析核心思想并提供Python代码实现,帮助理解在查找子数组和、字符串匹配和字符计数场景中的高效算法。

滑动窗口(核心思想)

  1. 滑动窗口适合子数组的搜索
  2. 同向双指针检索数组,通过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
            

  1. 通过计数判断是否满足条件

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
        
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值