ZhangZhihui's Blog  

Given two strings s and t of lengths m and n respectively, return the minimum window  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.

 

ChatGPT's Solution:

from collections import Counter


class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        
        if not t or not s:
            return ''
        
        t_counter = Counter(t)  # Count the frequency of characters in t
        current_counter = Counter()
        left = 0
        min_len = float("inf")
        min_window = ""
        required_chars = len(t_counter)  # Number of unique characters in t
        formed_chars = 0  # Number of unique chracters in the window that match t

        for right, char in enumerate(s):
            current_counter[char] += 1
            if current_counter[char] == t_counter[char]:
                formed_chars += 1
            
            # Try to shrink the window from the left while it still contains all characters of t
            while formed_chars == required_chars:
                window_len = right - left + 1
                if window_len < min_len:
                    min_len = window_len
                    min_window = s[left:right + 1]
                
                # Remove the leftmost character from the window
                current_counter[s[left]] -= 1
                if s[left] in t_counter and current_counter[s[left]] < t_counter[s[left]]:
                    formed_chars -= 1
                left += 1
        
        return min_window  # Return the minimum window found, or "" if no valid window exists

 

 

posted on 2025-03-15 17:31  ZhangZhihuiAAA  阅读(18)  评论(0)    收藏  举报