给定一个较长字符串big和一个包含较短字符串的数组smalls,设计一个方法,根据smalls中的每一个较短字符串,对big进行搜索。输出smalls中的字符串在big里出现的所有位置positions,其中positions[i]为smalls[i]出现的所有位置。
示例:
输入:
big = “mississippi”
smalls = [“is”,“ppi”,“hi”,“sis”,“i”,“ssippi”]
输出: [[1,4],[8],[],[3],[1,4,7,10],[5]]
提示:
0 <= len(big) <= 1000
0 <= len(smalls[i]) <= 1000
smalls的总字符数不会超过 100000。
你可以认为smalls中没有重复字符串。
所有出现的字符均为英文小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/multi-search-lcci
class Solution:
def __init__(self):
self.Trie = {} # 构造字典树
def insert(self, word:str):
'''建字典树,插入值'''
p = self.Trie
for w in word:
if p.get(w, 0) == 0:
p[w] = {}
p = p[w]
p['*'] = True # 一个单词结束标志
def multiSearch(self, big: str, smalls: List[str]) -> List[List[int]]:
ans = []
dt = {} # 存储smalls中字符串的位置
for ind, word in enumerate(smalls):
'''enumerate(seq),返回下标和数据
以smalls中的字符串构造字典树
'''
ans.append([]) # 初始化
dt[word] = ind
self.insert(word)
for i in range(len(big)):
if big[i] in self.Trie:
pos = i
p = self.Trie
while pos < len(big) and big[pos] in p:
p = p[big[pos]]
if p.get('*', False):
ans[dt[big[i:pos+1]]].append(i)
pos += 1
return ans