leetcode python minimum-window-substring

minimum-window-substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S =“ADOBECODEBANC”
T =“ABC”

Minimum window is"BANC".

Note:
If there is no such window in S that covers all characters in T, return the emtpy string"".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

题意

在S中找到包含T的最小字串

思路

说着很简单,做起来还蛮难的,这道题我用了若干python简便语法,但是我做题不想调包,不然还是很好计算的。第一,设置miss变量(代码中有说明),第二,设置count变量,主要用来收缩边界。整体思路就是滑动窗口啊,先扩张右边界,找到同时包含T的字串。然后再收缩左边界。

python实现

class Solution:
    def minWindow(self, s, t):
        count = dict.fromkeys(t, 1)  # 统计字符串 t 中字符出现的次数, 结果是{'A': 1, 'B': 1, 'C': 1}
        miss = len(t)
        i = m = n = 0  # i为左边界,mn记录最小的结果
        for j, v in enumerate(s, 1):
            miss -= count[v] > 0 if v in count.keys() else 0  # 当一串字符同时包含ABC,miss的值才等于0
            count[v] = count.get(v, -1) - 1  # 凡是出现的都减去1
            if not miss:
                # print(count)
                while i < j and count[s[i]] < 0:  # 判断哪些边界可以收缩,其实主要是针对多余的字符,也针对多余的a
                    count[s[i]] += 1
                    i += 1  # 收缩左边界
                if not n or j - i <= n - m:  # 更新新的窗口
                    m, n = i, j
        return s[m:n]


if __name__ == '__main__':
    s = "AADOBECODEBANC"
    t = "ABC"
    so = Solution()
    print(so.minWindow(s, t))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值