题解 | #最小覆盖子串#
最小覆盖子串
http://www.nowcoder.com/practice/c466d480d20c4c7c9d322d12ca7955ac
滑动窗口+哈希
#
# @param S string字符串
# @param T string字符串
# @return string字符串
#
class Solution:
def minWindow(self , S: str, T: str) -> str:
# 维护两个哈希表,hashT表示需要的字符,hash1表示记录窗口内满足条件的字符
hashT = {}
for i in list(T):
if i not in hashT:
hashT[i] = 1
else:
hashT[i] += 1
# 一次遍历找“可行解”
res = ''
for i in range(len(S)):
# hash1 = hashT 默认深拷贝,等价于hash1 = hashT.deepcopy()
hash1 = hashT.copy()
if S[i] not in T:
continue
else:
# 右窗口移动
for j in range(i,len(S)):
if S[j] in hash1:
if hash1[S[j]] == 1:
del hash1[S[j]]
else:
hash1[S[j]] -= 1
# 判断窗口是否已包含所有子串
if len(hash1) == 0:
if res == '':
res = S[i:j+1]
elif j-i+1 < len(res):
res = S[i:j+1]
break
return res