class Trie:
# 构建字典树
def __init__(self,words):
self.d = {}
for word in words:
t = self.d
for w in word:
if w not in t:
t[w] = {}
t = t[w]
t['end'] = word
# print(self.d)
def search(self,s):
t = self.d
res = []
for w in s:
if w not in t:
break
t = t[w]
if 'end' in t:
res.append(t['end'])
return res
class Solution:
def multiSearch(self, big: str, smalls: List[str]) -> List[List[int]]:
"""
{'i': {'s': {'end': 'is'}, 'end': 'i'},
'p': {'p': {'i': {'end': 'ppi'}}},
'h': {'i': {'end': 'hi'}},
's': {'i': {'s': {'end': 'sis'}},
's': {'i': {'p': {'p': {'i': {'end': 'ssippi'}}}}}}}
"""
trie = Trie(smalls)
hit = collections.defaultdict(list)
for i in range(len(big)):
matchs = trie.search(big[i:])
for word in matchs:
hit[word].append(i)
res = []
for word in smalls:
res.append(hit[word])
return res
12-10
650
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交