LeetCode-76-Minimum Window Substring 尺取法+字典

来源:互联网 发布:java观察者模式例子 编辑:程序博客网 时间:2024/05/20 19:49


class Solution(object):    def minWindow(self, s, t):        """        :type s: str        :type t: str        :rtype: str        """        Map={}        Lens=len(s)        Lent=len(t)        p=-1        OK=0        for i in range(Lent):            if t[i] not in Map:                Map[t[i]]=(1,0)#(should be,now have)                OK+=1            else:                Map[t[i]]=(Map[t[i]][0]+1,0)        for i in range(Lens):            if s[i] in Map:                Map[s[i]]=(Map[s[i]][0],Map[s[i]][1]+1)                if Map[s[i]][0]==Map[s[i]][1]:OK-=1            if OK==0:                p=i                break        if p==-1:return ""        curl=0        curr=p        Len=p+1        ansl=0        ansr=p        #print Map        while(True):            if OK==0:                if s[curl] in Map:                    Map[s[curl]]=(Map[s[curl]][0],Map[s[curl]][1]-1)                    if Map[s[curl]][1]<Map[s[curl]][0]:                        OK+=1                        curl+=1                        continue                curl+=1                if curr-curl<Len:                    Len=curr-curl+1                    ansl=curl                    ansr=curr            else:                curr+=1                if curr==Lens:                    break                if s[curr] in Map:                    Map[s[curr]]=(Map[s[curr]][0],Map[s[curr]][1]+1)                    if Map[s[curr]][1]==Map[s[curr]][0]:                        OK-=1                        if OK==0:                            if curr-curl<Len:                                Len=curr-curl+1                                ansl=curl                                ansr=curr        #print ansl,ansr        return s[ansl:ansr+1]                


原创粉丝点击