leetcode--滑动窗口

3. 无重复字符的最长子串

用一个队列存储for循环的字母,如果字母在队列中,就把所有的该元素之前的元素全部pop掉,否则append进去,同时记录最长长度

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        queue = collections.deque()
        n, max_length, start, cur_length = len(s), 0, 0, 0
        for i in range(n):
            if s[i] not in queue:
                queue.append(s[i])
                cur_length += 1
            else:

                while queue and queue[0] != s[i]:
                    queue.popleft()
                    cur_length -= 1
                queue.popleft()
                queue.append(s[i])
            if cur_length > max_length:
                max_length = cur_length
        return max_length

76. 最小覆盖子串

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        dic_s, dic_t = collections.defaultdict(int), collections.defaultdict(int)
        for i in t:
            dic_t[i] += 1
        i, satrt, end = 0, 0, float("inf")
        need = len(t)
        for j in range(len(s)):
            if dic_t[s[j]] > 0:
                need -= 1
            dic_t[s[j]] -= 1
            if need == 0:
                while dic_t[s[i]] < 0:
                    dic_t[s[i]] += 1
                    i += 1
                if j - i < end - satrt:
                    satrt, end = i, j
                    dic_t[s[i]] += 1
                    i += 1
                    need += 1
        return s[satrt:end+1] if end - satrt <= len(s) else ""

239. 滑动窗口最大值

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        queue = collections.deque()
        res = []
        for i in range(len(nums)):
            while queue and nums[i] >= nums[queue[-1]]:
                queue.pop()
            queue.append(i)
            if i - queue[0] >= k:
                queue.popleft()
            res.append(nums[queue[0]])
                
        return res[k-1:]

438. 找到字符串中所有字母异位词

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        if len(s) < len(p):
            return []
        dic_p, dic_s, res = collections.defaultdict(int), collections.defaultdict(int), []
        for i in p:
            dic_p[i] += 1
        i = j = 0
        while j < len(s):
            dic_s[s[j]] += 1
            while dic_s[s[j]] > dic_p[s[j]]:
                dic_s[s[i]] -= 1
                i += 1
                
            if j - i + 1 == len(p):
                res.append(i)
                dic_s[s[i]] -= 1
                i += 1
            j += 1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值