Skip to content

76.Minimum Window Substring

题目

Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

The testcases will be generated such that the answer is unique.

 

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.

 

Constraints:

  • m == s.length
  • n == t.length
  • 1 <= m, n <= 105
  • s and t consist of uppercase and lowercase English letters.

 

Follow up: Could you find an algorithm that runs in O(m + n) time?

Related Topics
  • 哈希表
  • 字符串
  • 滑动窗口

  • 👍 3256
  • 👎 0
  • 思路

    滑动窗口经典题型,变长滑动窗口,主要是两个时机的确定,何时进入窗口,何时收缩窗口

    • 创建窗口,当字符出现在 needs ,进入窗口
    • 窗口收缩: 窗口字符数量大于 needs 时开始收缩,left收缩至第一个有效字符位置后,再统计结果

    解法一

    窗口和目标的比较采用 Counter 比较,判断是否需要窗口收缩

    python
        def minWindow(self, s: str, t: str) -> str:
            window = defaultdict(int)
            needs = Counter(t)
            res = ''
            windowQueue = deque()
    
            left = right = 0
            while right < len(s):
                char = s[right]
                if char in needs:
                    window[char] += 1
                    windowQueue.append(right)
    
                right += 1
    
                # shrink the window to the mini set
                while Counter(window) >= needs:
                    # left 跳至 s 的有效字符位置
                    left = windowQueue.popleft()
                    if res == '' or right - left < len(res):
                        res = s[left: right]
    
                    # 收缩窗口,更新 left 位置
                    remove_char = s[left]
                    window[remove_char] -= 1
    
                    # left 跳至 s 下一个有效字符位置
                    if windowQueue:
                        left = windowQueue[0]
    
            return res

    复杂度分析

    • 时间复杂度O(N)
    • 空间复杂度O(N)