题目
    76.最小覆盖子串
    image.png

    思路
    滑动窗口。关键在于判断窗口中的字符串是否包含T中所有字母
    from collections import Counter

    1. class Solution:
    2. def minWindow(self, s: str, t: str) -> str:
    3. def is_contained(window, t):
    4. # dict
    5. window = dict(window)
    6. t = dict(t)
    7. for t_key, t_val in t.items():
    8. if window.__contains__(t_key):
    9. if window[t_key] < t_val:
    10. return False
    11. else:
    12. return False
    13. return True
    14. t = Counter(t)
    15. left = right = 0
    16. window = {}
    17. min_substr = list(s)
    18. while right < len(s):
    19. window[s[right]] = window.get(s[right], 0) + 1
    20. while is_contained(window, t):
    21. if right-left+1 <= len(min_substr):
    22. min_substr = s[left:right+1]
    23. window[s[left]] -= 1
    24. left += 1
    25. right += 1
    26. return min_substr if type(min_substr) is str else ''

    超时做法

    1. class Solution:
    2. def minWindow(self, s: str, t: str) -> str:
    3. def is_contained(sub_s, t):
    4. sub_s = list(sub_s)
    5. for c in t:
    6. if c in sub_s[:]:
    7. sub_s.remove(c)
    8. else:
    9. return False
    10. else:
    11. return True
    12. left = 0
    13. right = 0
    14. min_substr = s
    15. Flag = False
    16. while right < len(s):
    17. right += 1
    18. while is_contained(s[left:right], t) and left < right:
    19. print('ok')
    20. if len(s[left:right]) <= len(min_substr):
    21. print('fuzhi')
    22. min_substr = s[left:right]
    23. Flag = True
    24. print(min_substr)
    25. left += 1
    26. return min_substr if Flag else ''

    别人简洁的代码

    1. class Solution:
    2. def minWindow(self, s: str, t: str) -> str:
    3. ans=''
    4. l=0
    5. minn=99999
    6. d=Counter(t)
    7. dd=defaultdict(int)
    8. for i in range(len(s)):
    9. dd[s[i]]+=1
    10. while involve(d,dd):
    11. if i-l<minn:
    12. minn=i-l
    13. ans=s[l:i+1]
    14. dd[s[l]]-=1
    15. l+=1
    16. return ans
    17. def involve(a,b):
    18. for k,v in a.items():
    19. if k not in b or b[k]<v:
    20. return False
    21. return True
    22. 作者:cpf_china
    23. 链接:https://leetcode-cn.com/problems/minimum-window-substring/solution/python3-by-cpf_china-10/
    24. 来源:力扣(LeetCode
    25. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。