代码改变世界

[LeetCode] 76. Minimum Window Substring_Hard tag: two pointers

2021-08-08 09:27  Johnson_强生仔仔  阅读(26)  评论(0编辑  收藏  举报

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.

A substring is a contiguous sequence of characters within the string.

 

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?

Ideas: O(m + n)

1. 利用desire_window来记录相应char及应该有的个数,desire_num来记录有多少个char

2. 利用cur_window 来记录当前的char及有的个数, cur_num来记录有多少个char时符合应该有个个数

3. ans # 1st 记录长度, 2nd 记录当前的最短string

4. r 往右移,更新cur_window 和cur_num, 如果cur_num == desire_num, 那么看是否为ans,同时l 右移直到cur_num != desire_num or l > r

5. 最后返回ans[1] if ans[1] else ""

 

Code:

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        desire_window, ans, n, cur_window, cur_num = collections.Counter(t), [None, None], len(s), collections.Counter(), 0
        desire_num, l, r = len(desire_window), 0, 0
        while r < n:
            c_r = s[r]
            cur_window[c_r] += 1
            if cur_window[c_r] == desire_window[c_r]:
                cur_num += 1
            while cur_num == desire_num and l <= r:
                if ans[0] is None or r - l + 1 < ans[0]:
                    ans = [r - l + 1, s[l:r + 1]]
                c_l = s[l]
                cur_window[c_l] -= 1
                if cur_window[c_l] < desire_window[c_l]:
                    cur_num -= 1
                l += 1
            r += 1
        return ans[1] if ans[1] else ""