题目:原题链接(困难)
标签:字典树
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | 构造 = O ( N × S 2 ) O(N×S^2) O(N×S2) ; f = O ( S ) O(S) O(S) | O ( S 2 ) O(S^2) O(S2) | 3208ms (5.32%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
class Trie:
class _Node:
def __init__(self):
self.value = None
self.weight = 0
self.children = {}
def __contains__(self, ch):
return ch in self.children
def __getitem__(self, ch):
return self.children[ch]
def __setitem__(self, ch, value):
self.children[ch] = value
def __init__(self):
self.root = self._Node()
def add(self, word, weight=1):
"""向字典树中添加词语"""
node = self.root
for ch in word:
if ch not in node:
node[ch] = self._Node()
node.weight = max(node.weight, weight)
node = node[ch]
node.value = word
node.weight = weight
def __contains__(self, word):
"""判断词语是否存在"""
node = self.root
for ch in word:
if ch not in node:
return False
node = node[ch]
return node.value == word
def search(self, string):
"""寻找字符串中从头开始的第1个词语(如果没有找到则返回None)"""
node = self.root
for ch in string:
if ch not in node:
return "", -1
node = node[ch]
if node.value is not None:
return node.value, node.weight
return "", -1
def start_with(self, string):
"""寻找字符串中是否有以string开头的"""
node = self.root
for ch in string:
if ch not in node:
return "", -1
node = node[ch]
return node.value, node.weight
class WordFilter:
def __init__(self, words: List[str]):
self.trie = Trie()
for weight, word in enumerate(words):
code = word + "#" + word
for i in range(len(word) + 1):
self.trie.add(code[i:], weight=weight)
def f(self, prefix: str, suffix: str) -> int:
code = suffix + "#" + prefix
return self.trie.start_with(code)[1]