在Python中实现字典树(Trie)通常涉及以下步骤:
1. 定义TrieNode类,每个节点包含一个字典(children),用于存储子节点,以及一个布尔值(is_word),表示该节点是否为一个单词的结尾。
2. 定义Trie类,包含一个根节点,并提供插入(insert)、搜索(search)和前缀搜索(search_prefix)等方法。
class TrieNode:
def __init__(self):
self.children = {} 子节点字典
self.is_word = False 是否为单词结尾
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str):
curr = self.root
for char in word:
if char not in curr.children:
curr.children[char] = TrieNode()
curr = curr.children[char]
curr.is_word = True
def search(self, word: str) -> bool:
curr = self.root
for char in word:
if char not in curr.children:
return False
curr = curr.children[char]
return curr.is_word
def starts_with(self, prefix: str) -> bool:
curr = self.root
for char in prefix:
if char not in curr.children:
return False
curr = curr.children[char]
return True
使用示例:
trie = Trie()
trie.insert("apple")
print(trie.search("apple")) 输出: True
print(trie.search("app")) 输出: False
print(trie.starts_with("app")) 输出: True
trie.insert("app")
print(trie.search("app")) 输出: True
这个实现支持插入单词和搜索单词,同时也支持搜索前缀。你可以根据需要扩展这个实现,比如添加删除单词的功能或者支持更多字符。