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)