给定字符串S和字符串T,找到S中的最小窗口 将包含复杂度为O(n)的T中的所有字符。
示例:
Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC"
注意:
- 如果S中没有覆盖T中所有字符的窗口,请返回空字符串“”。
- 如果有这样的窗口,可以保证S中始终只有一个唯一的最小窗口。
我在下面编写了python代码,该代码在主字符串“ s”中找到模式字符串“ t”的所有字符都在其中的所有窗口。但是我无法最小化该窗口并保持O(n)的时间复杂度。所以请在下面的python代码中帮助我:-
def min_window_size(s,t):
begin=0
end=0
dict={}
list=[]
count=0
len_t=len(t)
#Creating character counts in string "t" to be searched
for c in t:
dict.setdefault(c,0)
dict[c]+=1
print(s+" "+t)
#Iterating over main string "s" where minimum window need to be checked
for i in range (len(s)):
if s[i] in dict:
#Increasing the counter whenever character from "t" is found in "s"
count+=1
end+=1
#As soon as count equal to length of string "t" it means we have found all characters of "t" in "s"
if count==len_t:
#Appending the found window into empty list
list.append(s[begin:end])
index=begin
#Increase begin counter to forward so that next window after first can be searched
begin=end
#Reset counter so that we can continue to look for new window
count=0
print list
if list==[]:
return " "
else:
return (min(list,key=len))
此练习是我学习过程的一部分,有以下问题