最小窗口子串

时间:2019-02-11 15:39:41

标签: python window substring minimum

  

给定字符串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))

此练习是我学习过程的一部分,有以下问题

  1. 如何修改代码,以便也可以开始最小化字符串“ t”的所有字符所在的窗口?
  2. 在我的代码中,我正在考虑检查单个找到的窗口,然后尝试通过移动begin指针来缩小窗口,但是我无法在当前程序中提供相同的sudo代码或实际python代码。
  3. 为了学习并使我的逻辑健壮,我应该采取什么方法?通常情况下,我会遇到问题吗?这是正确的方法吗?对此有任何帮助或指导。

0 个答案:

没有答案