minimum-window-substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S =“ADOBECODEBANC”
T =“ABC”
Minimum window is"BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string"".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
题意
在S中找到包含T的最小字串
思路
说着很简单,做起来还蛮难的,这道题我用了若干python简便语法,但是我做题不想调包,不然还是很好计算的。第一,设置miss变量(代码中有说明),第二,设置count变量,主要用来收缩边界。整体思路就是滑动窗口啊,先扩张右边界,找到同时包含T的字串。然后再收缩左边界。
python实现
class Solution:
def minWindow(self, s, t):
count = dict.fromkeys(t, 1) # 统计字符串 t 中字符出现的次数, 结果是{'A': 1, 'B': 1, 'C': 1}
miss = len(t)
i = m = n = 0 # i为左边界,mn记录最小的结果
for j, v in enumerate(s, 1):
miss -= count[v] > 0 if v in count.keys() else 0 # 当一串字符同时包含ABC,miss的值才等于0
count[v] = count.get(v, -1) - 1 # 凡是出现的都减去1
if not miss:
# print(count)
while i < j and count[s[i]] < 0: # 判断哪些边界可以收缩,其实主要是针对多余的字符,也针对多余的a
count[s[i]] += 1
i += 1 # 收缩左边界
if not n or j - i <= n - m: # 更新新的窗口
m, n = i, j
return s[m:n]
if __name__ == '__main__':
s = "AADOBECODEBANC"
t = "ABC"
so = Solution()
print(so.minWindow(s, t))