題目:
最小覆蓋子串:給你一個字符串 S、一個字符串 T,請在字符串 S 里面找出:包含 T 所有字母的最小子串。
說明:
- 如果 S 中不存這樣的子串,則返回空字符串
""
。 - 如果 S 中存在這樣的子串,我們保證它是唯一的答案。
思路:
使用滑動窗口法。
程序:
from collections import defaultdict
class Solution:
def minWindow(self, s: 'str', t: 'str') -> 'str':
if not s or not t:
return ""
findOut = defaultdict(int)
for letter in t:
findOut[letter] += 1
index1 = 0
index2 = 0
counter = len(t)
length = len(s)
min_len = float("inf")
result = ""
while index2 < length:
if findOut[s[index2]] >= 1:
counter -= 1
findOut[s[index2]] -= 1
index2 += 1
while counter == 0:
if min_len > index2 - index1:
min_len = index2 - index1
result = s[index1 : index2]
if findOut[s[index1]] == 0:
counter += 1
findOut[s[index1]] += 1
index1 += 1
return result