LeetCode Minimum Window Substring

LeetCode解题之Minimum Window Substring


原题

给定两个字符串S和T,要求在O(n)的时间内找到包含T中所有字符的S的最短子字符串。

注意点:

  • 如果不存在满足要求的子字符串,则返回”“
  • 如果存在多个子字符串满足要求,可以保证其中只有一个最短的

例子:

输入: s = “ADOBECODEBANC”, t = “ABC”

输出: “BANC”

解题思路

通过前后指针来确定当前的子字符串,先不断移动后指针,直到子字符串中已经包含了所有T中的字符,尝试把前指针后移,并不断刷新最短长度和对应的起始位置,如果移动前指针后不再包含所有T中的字符,则继续移动后指针。交替移动前后指针,直到遍历完整个字符串S。

AC源码

from collections import defaultdict


class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        MAX_INT = 2147483647
        start = end = 0
        char_need = defaultdict(int)    # the count of char needed by current window, negative means current window has it but not needs it
        count_need = len(t)             # count of chars not in current window but in t
        min_length = MAX_INT
        min_start = 0
        for i in t:
            # current window needs all char in t
            char_need[i] += 1           
        while end < len(s):
            if char_need[s[end]] > 0:
                count_need -= 1
            # current window contains s[end] now, so does not need it any more
            char_need[s[end]] -= 1      
            end += 1
            while count_need == 0:
                if min_length > end - start:
                    min_length = end - start
                    min_start = start
                # current window does not contain s[start] any more
                char_need[s[start]] += 1    
                # when some count in char_need is positive, it means there is char in t but not current window
                if char_need[s[start]] > 0: 
                    count_need += 1
                start += 1
        return "" if min_length == MAX_INT else s[min_start:min_start + min_length]


if __name__ == "__main__":
    assert Solution().minWindow("ADOBECODEBANC", "ABC") == "BANC"

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值