LeetCode-76 Minimum Window Substring

Description

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).

Note:
• If there is no such window in S that covers all characters in T, return the empty string “”.
• If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

Example

Example:
Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”

Submissions

解题思路采用滑动窗口,通过变量L和R记录窗口左右端点位置,c记录当前窗口中目标字符串元素的个数,out代表当前窗口字符串。利用Counter类初始化目标字符串字典,后从左到右遍历s字符串,当遍历到目标字符串中元素时,判断字典中元素value是否大于0,若大于则c加一,value减一。当c等于目标字符串长度,即当前窗口内包含目标字符串时,判断out是否为空,或是否当前窗口长度小于out,若为空或小于,则将当前窗口字符串赋给out进行更新。L标记继续右移,当目标元素被滑出窗口时目标字符串字典中对应元素value和c进行更新。最后返回长度最小的out即可。

实现代码如下:

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        d = Counter(t)  
        L = 0
        c = 0
        out = ''
        for R in range(len(s)):
            if d[s[R]] > 0 :
                c+=1
            d[s[R]] -= 1
            while c == len(t):
                if not out or R-L+1 < len(out):
                    out = s[L:R+1]
                d[s[L]] +=1
                if d[s[L]] > 0:
                    c-=1
                L+=1
        return out

你可能感兴趣的:(python,leetcode)