0
点赞
收藏
分享

微信扫一扫

LeetCode-双指针

Villagers 2022-03-15 阅读 68

最小覆盖子串:

给出两个字符串 s 和 t,要求在 s 中找出最短的包含 t 中所有字符的连续子串。

class Solution:
    def minWindow(self , S , T ):

        lens=len(S)
        needcnt={}
        for i in T:
            needcnt[i]=1 if i not in needcnt else needcnt[i]+1
        totalneed=len(needcnt)
        minlen=len(S)+1
        minval=""
        i=0
        lasti=0
        while i<lens:
            if totalneed==0:
                while totalneed==0:
                    if minlen>=i-lasti:
                        minlen=i-lasti
                        minval=S[lasti:i]
                    if S[lasti] in needcnt:
                        needcnt[S[lasti]]=needcnt[S[lasti]]+1
                        if needcnt[S[lasti]]==1:
                            totalneed=totalneed+1
                    lasti=lasti+1
            else:
                if S[i] in needcnt:
                    needcnt[S[i]]=needcnt[S[i]]-1
                    if needcnt[S[i]]==0:
                        totalneed=totalneed-1
                i=i+1
        if i==lens:
            if totalneed==0:
                while totalneed==0:
                    if minlen>=i-lasti:
                        minlen=i-lasti
                        minval=S[lasti:i]
                    if S[lasti] in needcnt:
                        needcnt[S[lasti]]=needcnt[S[lasti]]+1
                        if needcnt[S[lasti]]==1:
                            totalneed=totalneed+1
                    lasti=lasti+1
        return minval
举报

相关推荐

0 条评论