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

本文介绍了一种寻找字符串s中包含字符串t所有字符的最短子串的算法实现。通过使用滑动窗口和哈希映射的方式,该算法能够有效地解决此问题,并详细展示了其实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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]
                


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值