python写算法题:leetcode: 30. Substring with Concatenation of All Words

115 篇文章 0 订阅

https://leetcode.com/problems/substring-with-concatenation-of-all-words/#/description

class Solution(object):
    def matchstr(self, p0, p1, wordsind, wlen, posmap):
        wv={}
        for w in wordsind.keys():
            wv[w]=0
        for i in xrange(p0, p1, wlen):
            if i in posmap:
                wv[posmap[i]]+=1
        return wv

    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        if len(words)==0: return []

        wlen = len(words[0])
        wordsind = {}
        wcnt={}
        posmap={}
        for w in words:
            if w in wordsind:
                wcnt[w]+=1
                continue
            else:
                matchlst=[]
                wcnt[w]=1
            i=0
            while i>=0:
                i = s.find(w, i)
                if i>=0:
                    posmap[i]=w
                    matchlst.append(i)
                    i+=1
            wordsind[w]=matchlst
        res=[]
        endpos=len(words)*wlen-wlen
        for p0 in xrange(len(words[0])):
            wv = self.matchstr(p0, p0+len(words)*wlen, wordsind, wlen, posmap)
            if wv == wcnt:
                res.append(p0)
            for p in xrange(p0+wlen, len(s)-endpos, wlen):
                if p-wlen in posmap:
                    wv[posmap[p-wlen]]-=1
                if p+endpos in posmap:
                    wv[posmap[p+endpos]]+=1
                if wv == wcnt:
                    res.append(p)
        return res

思路:充分利用匹配串长度相同规则,开头匹配偏移取值是单个匹配窜的长度范围,然后跳跃式的检查是否满足要求,最终运算复杂度为 O(n+m)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值