Trie 本身包含根节点和插入/查找函数
class Trie:
def __init__(self):
## Initialize this Trie (add a root node)
self.root = TrieNode()
def insert(self, word):
## Add a word to the Trie
current_node = self.root
for char in word:
if char not in current_node.children:
current_node.insert(char)
current_node = current_node.children[char]
current_node.is_word = True
def find(self, prefix):
## Find the Trie node that represents this prefix
current_node = self.root
for char in prefix:
if char not in current_node.children:
return None
current_node = current_node.children[char]
return current_node
这是一个用trie实现自动补全的类方法。
class TrieNode:
def __init__(self):
## Initialize this node in the Trie
self.is_word = False
self.children = {}
self.results = []
def insert(self, char):
## Add a child node in this Trie
self.children[char] = TrieNode()
def suffixes(self, suffix=''):
## Recursive function that collects the suffix for
## all complete words below this point
for char, node in self.children.items():
if node.is_word:
self.results.append(suffix + char)
if node.children:
self.results += node.suffixes(suffix + char)
results = self.results.copy()
self.results = []
return list(set(results))
可以使用以下命令获得解决方案。
MyTrie = Trie()
wordList = ["ant", "anthology", "antagonist", "antonym",
"fun", "function", "factory", "trie", "trigger", "trigonometry", "tripod"]
for word in wordList:
MyTrie.insert(word)
MyTrie.find('a').suffixes()
MyTrie.find('f').suffixes()
MyTrie.find('t').suffixes()
MyTrie.find('tri').suffixes()
MyTrie.find('anto').suffixes()