题目描述
给定两个字符串 s 和 t 。返回 s 中包含 t 的所有字符的最短子字符串。如果 s 中不存在符合条件的子字符串,则返回空字符串 “” 。
如果 s 中存在多个符合条件的子字符串,返回任意一个。
注意: 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
题目链接
解题思路
主要使用哈希表结合滑窗的思路来解题。
使用哈希表来记录目标串t中包含字符出现的次数。
使用滑动窗口来搜索满足条件的子串,并比较长度。右指针移动时满足条件的字符,计数减1。左指针移动时满足条件的字符加1。
代码实现
def minWindow(s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
win_codes={}
need_count=len(t)
res=[0, len(s)+1]//字符串长度相同时也可以判断
left=0
for code in t:
if code not in win_codes:
win_codes[code]=1
else:
win_codes[code]+=1
for right in range(len(s)):
if s[right] in win_codes:
if win_codes[s[right]] > 0:
need_count-=1
win_codes[s[right]]-=1
while need_count <= 0 and left <= right:
if right-left < res[1]-res[0]:
res=[left, right]
if s[left] in win_codes:
if win_codes[s[left]] >= 0:
need_count+=1
win_codes[s[left]]+=1
left+=1
if res==[0, len(s)+1]:
return ""
else:
return s[res[0]:res[1]+1]
心得:清醒时多读书,糊涂时多睡觉。睡觉真是个好东西。