【Leetcode】30. Substring with Concatenation of All Words 串联所有单词的子串
解法
关键在于所有的单词长度都相同
最简单的方法就是依次判断每个下标i符不符合条件
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if len(words)==0:
return []
from collections import defaultdict,Counter
wid = defaultdict()
wid.default_factory = wid.__len__
counter = Counter()
for w in words:
counter[wid[w]] += 1
l = len(words)
m = len(words[0])
n = len(s)
f = [-1]*n
for i,c in enumerate(s[:n-m+1]):
substr = s[i:i+m]
if substr in wid:
f[i] = wid[substr]
def check(i):
mine = Counter([f[x] for x in xrange(i,i+m*l,m)])
return sum((mine-counter).values())==0
ans = filter(lambda x:check(x),xrange(n-m*l+1))
return ans
为了减少重复计算,假设单词长度为4,单词数为5,对于0,4,8,…这一系列下标,可以用一个长度为5的滑动窗口来统计
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if len(words)==0:
return []
from collections import defaultdict,Counter
wid = defaultdict()
wid.default_factory = wid.__len__
counter = Counter()
for w in words:
counter[wid[w]] += 1
l = len(words)
m = len(words[0])
n = len(s)
f = [-1]*n
for i,c in enumerate(s[:n-m+1]):
substr = s[i:i+m]
if substr in wid:
f[i] = wid[substr]
ans = []
for b in xrange(m):
if b+l*m>n:break
mine = Counter([f[x] for x in xrange(b,b+l*m,m)])
if sum((mine-counter).values())==0:
ans.append(b)
for r in xrange(b+l*m,n,m):
mine[f[r]] += 1
mine[f[r-l*m]] -= 1
if sum((mine-counter).values())==0:
ans.append(r-l*m+m)
return ans