Intuition
The problem involves finding the minimum window substring of string s that contains all characters of string t. The goal is to efficiently track the window and identify the minimum length substring that satisfies the condition.
Approach
The provided solution uses a two-pointer sliding window approach to iterate through the string s and maintain the counts of characters in the current window. It also uses two dictionaries (count and window) to keep track of the required and actual counts of characters.
Initialize the dictionaries count and window to store the required and actual counts of characters in t and the current window, respectively.
Iterate through each character in t and update the count in the count dictionary.
Initialize variables have and need to keep track of the number of characters in the window that match the required counts and the total number of required characters, respectively.
Initialize variables res and resl to store the minimum window substring indices and length.
Use two pointers, l and r, to represent the left and right boundaries of the window. Move the right pointer (r) through the string s:
Update the count of the current character in the window dictionary.
If the current character is in count and its count in the window matches the required count, increment have.
While have equals need (all required characters are in the window):
Check if the current window length is smaller than the current minimum length (resl).
Update res and resl with the current window indices and length.
Decrement the count of the character at the left boundary (l) and update have accordingly.
Move the left boundary (l) to the right.
Return the minimum window substring from the indices stored in res or an empty string if no such substring is found.
Complexity
- Time complexity:
The time complexity of this solution is O(m + n), where m is the length of string s and n is the length of string t. The solution iterates through both strings once.
- Space complexity:
The space complexity is O(n), where n is the length of string t. The space used is proportional to the size of t to store the required counts in the count dictionary.
Code
class Solution:
def minWindow(self, s: str, t: str) -> str:
if t == '': return ''
count,window = {},{}
for c in t:
count[c] = 1 + count.get(c,0)
have,need = 0 , len(count)
res,resl = [-1 , -1],float('infinity')
l = 0
for r in range(len(s)):
c = s[r]
window[c] = 1 + window.get(c,0)
if c in count and window[c] == count[c]:
have += 1
while have == need:
if (r - l + 1) < resl:
res = [l , r]
resl = (r - l + 1)
window[s[l]] -= 1
if s[l] in count and window[s[l]] < count[s[l]]:
have -= 1
l += 1
l , r =res
return s[l:r+1] if resl != float('infinity') else ''
文章介绍了使用滑动窗口方法解决寻找包含给定字符串t中所有字符的最小窗口子串的问题。通过维护当前窗口内字符的计数和所需字符计数,找到满足条件的最小子串。时间复杂度为O(m+n),空间复杂度为O(n)。
380

被折叠的 条评论
为什么被折叠?



