如果前缀为单词,则可以将Trie节点呈现为defaultdict
已扩展为包含布尔标志标记的对象。然后,你可以有地方在第一轮添加的所有的话特里和第二轮检查每个字两遍处理,如果它是一个组合或不:
from collections import defaultdict
class Node(defaultdict):
def __init__(self):
super().__init__(Node)
self.terminal = False
class Trie():
def __init__(self, it):
self.root = Node()
for word in it:
self.add_word(word)
def __contains__(self, word):
node = self.root
for c in word:
node = node.get(c)
if node is None:
return False
return node.terminal
def add_word(self, word):
node = self.root
for c in word:
node = node[c]
node.terminal = True
def is_combination(self, word):
node = self.root
for i, c in enumerate(word):
node = node.get(c)
if not node:
break
# If prefix is a word check if suffix can be found
if node.terminal and word[i+1:] in self:
return True
return False
lst = ["race", "racecar", "car"]
t = Trie(lst)
print([w for w in lst if t.is_combination(w)])
输出:
['racecar']
'我已经能够实现trie和和函数来获取一个单词的所有前缀“发布到目前为止您尝试过的内容。然后人们可以在你的代码上写字。 –