lc 76. Minimum Window Substring

https://leetcode.com/problems/minimum-window-substring/

滑动窗口

1.如果要求只要出现就算,也就是所t='a'和t='aa'是一样的话,那么记录一个出现过的字符的dict,只要这个set和目标set一样大,就可以去记录一下结果。这个结果可能是窗口右边移动产生,也可能是窗口左边移动产生的。

然后右界负责产生合法的,左界负责使之不合法。

2.如果是不光要出现,还要满足数量要求的话,就都要用dict了。一旦一次右边的移动导致d[c]==s[c]就是卡到了上界,那么nums+=1,就是记录几个字符满足了数量要求。

一旦一次左边的移动导致d[c]==s[c]-1那么nums-=1。每次我们用nums==len(s)来判断是否是一个合法窗。

trick:

要两层while嵌套,不要用并列的while:

while 不合法:

  j+=1 并且更新状态

 while 合法:

    记录一下

    i+=1 并且更新状态

代码:

class Solution:
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        ss={}
        d={}
        for c in t:
            d[c]=0
            if c in ss:
                ss[c]+=1
            else:
                ss[c]=1
        t=ss
        nums=0

        ans=[]
        i,j=0,-1
        while nums<len(t) and j+1<len(s): # not satisfy
            j+=1
            c=s[j]
            if c in t:
                d[c]+=1
                if d[c]==t[c]:
                    nums+=1
            while nums>=len(t) and i<len(s):
                if len(ans) == 0 or ans[1] - ans[0] > j - i:
                    ans = [i, j]
                c=s[i]
                if c in t:
                    if d[c]==t[c]:
                        nums-=1
                    d[c]-=1
                i+=1
        if len(ans)==0:
            return ''
        return s[ans[0]:ans[1]+1]

猜你喜欢

转载自www.cnblogs.com/waldenlake/p/10250183.html