【发布时间】:2018-04-28 14:36:17
【问题描述】:
我设法构造了一个 Trie,现在我想返回与 Trie 中的前缀匹配的字符串,但我在编写搜索函数时遇到了问题。
例如,如果我有一个前缀“aa”,我希望将字符串“aa”和“aac”作为输出。
class Node:
def __init__(self):
self.children = [None] * 26
self.end = False
self.value = ""
class Trie:
def __init__(self):
self.root = Node()
def add_word(self, key):
word_length = len(key)
current = self.root
for i in range(word_length):
position = self.ord_char(key[i])
if current.children[position] is None:
current.children[position] = Node()
current = current.children[position]
current.value = key[i]
current.end = True
def ord_char(self,key):
ord_rep = ord(key) - ord('a')
return ord_rep
def prefix_search(self, prefix):
lst = []
current = self.root
prefix_length = len(prefix)
for c in range(prefix_length):
c_position = self.ord_char(prefix[c])
current = current.children[c_position]
lst.append(current.value)
#doesnt seem like I'm doing it right
if __name__ == "__main__":
trie = Trie()
trie.add_word("aa")
trie.add_word("aac")
trie.add_word("b")
trie.prefix_search("aa")
我想通过搜索功能将字母组合在一起形成最终的字符串,但我想不出更好的方法。
【问题讨论】: