博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 76 最小覆盖子串
阅读量:2134 次
发布时间:2019-04-30

本文共 1098 字,大约阅读时间需要 3 分钟。

给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。

注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。

示例 1:

输入:s = "ADOBECODEBANC", t = "ABC"

输出:"BANC"

示例 2:

输入:s = "a", t = "a"

输出:"a"

解题思路:滑动窗口

class Solution:    def minWindow(self, s: str, t: str) -> str:        window = {}        need = {}        for i in t:            need[i] = need.setdefault(i, 0) + 1        left, right = 0, 0        valid = 0        max_len = float("inf")        start = 0        while right < len(s):            c = s[right]            right += 1            if c in need:                window[c] = window.setdefault(c, 0) + 1                if need[c] == window[c]:                    valid += 1            while valid == len(need):                if right - left < max_len:                    max_len = right - left                    start = left                d = s[left]                left += 1                if d in need:                    if window[d] == need[d]:                        valid -= 1                    window[d] -= 1        return "" if max_len == float("inf") else s[start:start + max_len]

转载地址:http://qwygf.baihongyu.com/

你可能感兴趣的文章
【深度学习】LSTM的架构及公式
查看>>
【python】re模块常用方法
查看>>
剑指offer 19.二叉树的镜像
查看>>
剑指offer 20.顺时针打印矩阵
查看>>
剑指offer 21.包含min函数的栈
查看>>
剑指offer 23.从上往下打印二叉树
查看>>
剑指offer 25.二叉树中和为某一值的路径
查看>>
剑指offer 34.把数组排成最小的数
查看>>
剑指offer 35.数组中只出现一次的数字
查看>>
剑指offer 58. 链表中环的入口结点
查看>>
剑指offer 60. 不用加减乘除做加法
查看>>
Leetcode C++《热题 Hot 100-13》234.回文链表
查看>>
Leetcode C++《热题 Hot 100-14》283.移动零
查看>>
Leetcode C++《热题 Hot 100-15》437.路径总和III
查看>>
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>