LeetCode 76. Minimum Window Substring--Python实现

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 empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S

题意就是从源串中返回一个包含目标字串的最小字串,这题和第3题和第30题类似,主要是确定start和end的位置,此题中引入了两个字典作为辅助 变量来进行分析判断。具体代码说明如下。

        tcount1={}#用来存储中字符串出现的次数。tcount1在下面会有增减变化,tcount2不变只做标准参考
        tcount2={}
        for char in t:
            if char not in tcount1:
                tcount1[char]=1
                tcount2[char]=1
            else:
                tcount1[char]+=1
                tcount2[char]+=1
        start=0  #字串开始的首位置,
        minstart=0
        scount=len(t) 
        minsize=len(s)+1 #s[start:start+minsize],不包括start+minsize,所以要加1
        for end in range(len(s)):  #字串结束的未位置
            if s[end] in tcount2 and tcount2[s[end]]>0:
                tcount1[s[end]]-=1
                if  tcount1[s[end]] >= 0:#上面是先减的啊所以可以是0啊
                    scount-=1
                if scount==0: #表明从当前的s[start]到s[end]包含了t了 ,到这一步必然s中有t,必然有end-start+1,小于len(s)+1
                    while True:
                        if s[start] in tcount2 and tcount2[s[start]]>0:
                            if  tcount1[s[start]] < 0: 
                                 tcount1[s[start]]+=1
                            else:
                                break
                        start+=1
                    if minsize > end-start+1:    
                        minsize=end-start+1
                        minstart=start
        
        if minsize < len(s)+1:
            return s[minstart:minstart+minsize]
        else:
            return ''


你可能感兴趣的:(LeetCode,算法,Python)