Leetcode: Minimum Window Substring

来源:互联网 发布:淘宝森马官方旗舰店 编辑:程序博客网 时间:2024/06/10 18:03

Question

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.

Hide Tags Hash Table Two Pointers String
Hide Similar Problems (H) Substring with Concatenation of All Words (M) Minimum Size Subarray Sum (H) Sliding Window Maximum


Solution

Get idea from here, here2, here3

class Solution(object):    def minWindow(self, s, t):        """        :type s: str        :type t: str        :rtype: str        """        dictn = {}        for elem in t:            if elem in dictn:                dictn[elem] += 1            else:                dictn[elem] = 1        cnt, l, minl, minsize = 0, 0, 0, len(s)+1        for r in range(len(s)):            if s[r] in dictn:                dictn[s[r]] -= 1                if dictn[s[r]]>=0:                    cnt += 1                while cnt==len(t):                    if r-l+1<minsize:                        minl = l                        minsize = r-l+1                    if s[l] in dictn:                        dictn[s[l]] += 1                        if dictn[s[l]]>0:                            cnt -= 1                    l += 1        if minsize>len(s):            return ''        return s[minl:minl+minsize]
0 0
原创粉丝点击