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
每日一道Leetcode - 面试题 17.17. 多次搜索 【字典树】
最新推荐文章于 2021-09-15 15:22:33 发布