标签:enumerate https 出现 result move note bec res leetcode
https://leetcode-cn.com/problems/minimum-window-substring/
给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。
示例:
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
说明:
如果 S 中不存这样的子串,则返回空字符串 ""。
如果 S 中存在这样的子串,我们保证它是唯一的答案。
class Solution:
def minWindow(self, s: str, t: str) -> str:
# - sanity check
if not t:
return ‘‘
# - statistic for t
t_dict = {}
for c in t:
if c not in t_dict:
t_dict[c] = 0
t_dict[c] += 1
# - use 2 pointers to solve
cnt = 0 # - count of t chars in sub string
min_len = len(s) + 1 # - min len of sub string
res = ‘‘ # - result string
left = 0 # - left pointer, init as 0
for i,c in enumerate(s):
# - handle only if c is one of t
if c not in t_dict:
continue
# - note: t_dict[c] could be minor int
t_dict[c] -= 1
if t_dict[c] == 0:
cnt += 1
# - if chars in t are all in this sub string,
# - check len of sub string
while cnt == len(t_dict):
# - update res
if i - left + 1 < min_len:
res = s[left:i+1]
min_len = len(res)
# - before move left pointer
ch = s[left]
if ch in t_dict:
# - cnt-1 only if t_dict[ch] > 0
t_dict[ch] += 1
if t_dict[ch] > 0:
cnt -= 1
# - move left pointer forward 1 step
left += 1
return res
[LeetCode in Python] 76 (H) minimum window substring 最小覆盖子串
标签:enumerate https 出现 result move note bec res leetcode
原文地址:https://www.cnblogs.com/journeyonmyway/p/12547087.html