[Leetcode]76. Minimum Window Substring @python

题目

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 empty string “”.

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

题目要求

给定字符串s和目标字符串t,要在s中找到一个最小的窗口,其中出现了所有t中的字符。

解题思路

解这道题需要注意,t中的字符可能为重复字符,所以需要用字典记录每个字符出现的次数。要判断窗口中是否出现了所有字符,首先需要左右指针表示窗口的位置,同时要有另外一个字典记录窗口中每个字符出现的次数。另外一个变量记录窗口中t内的字符出现的次数。

代码

class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        count = len(t)
        minileft = 0
        miniSize = len(s) + 1
        left = 0
        cmap1 = {}
        cmap2 = {}
        for c in t:
            if c not in cmap1:
                cmap1[c] = 1
                cmap2[c] = 1
            else:
                cmap1[c] += 1
                cmap2[c] += 1

        for right in range(len(s)):
            if s[right] in cmap1:
                cmap2[s[right]] -= 1
                if cmap2[s[right]] >= 0:
                    count -= 1
                if count == 0:
                        while True:
                            if s[left] in cmap2:
                                if cmap2[s[left]] < 0:
                                    cmap2[s[left]] += 1
                                else:
                                    break 
                            left += 1

                        if right - left + 1 < miniSize:
                            minileft = left
                            miniSize = right - minileft + 1

        if miniSize < len(s) + 1:
            return s[minileft:minileft + miniSize]
        else:
            return ''

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