如果前綴爲單詞,則可以將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和和函數來獲取一個單詞的所有前綴「發佈到目前爲止您嘗試過的內容。然後人們可以在你的代碼上寫字。 –