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.
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
andt
consist of uppercase and lowercase English letters.
class Solution:
def minWindow(self, s: str, t: str) -> str:
if t == "" : return ""
ct, sw = {}, {}
for c in t:
ct[c] = 1 + ct.get(c,0) #{'A': 1, 'B': 1, 'C': 1}
ardy ,req =0, len(ct)
ans, alen = [-1, -1], float("infinity")
l = 0 #left
#for right
for r in range(len(s)):
c = s[r]
sw[c] = 1 + sw.get(c,0)
if c in ct and sw[c]==ct[c]:
ardy += 1
while ardy == req:
if (r-l+1) < alen :
ans = [l,r]
alen = (r-l+1)
sw[s[l]] -= 1
if s[l] in ct and sw[s[l]] < ct[s[l]]:
ardy -= 1
l += 1
l, r = ans
return s[l:r+1] if alen != float("infinity") else ""
Explaination
Comments
Post a Comment