前缀树
208. 实现 Trie (前缀树)
难度 ⭐⭐
实现一个 Trie (前缀树),包含 insert
, search
, 和 startsWith
这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
Trie有什么用?
1. 自动补全
2. 拼写检查
coding
python
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
self.is_end = "is_end"
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur_node = self.root
for c in word:
cur_node = cur_node.setdefault(c,{})
cur_node[self.is_end] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
cur_node = self.root
for c in word:
if c not in cur_node:
return False
cur_node = cur_node[c]
return True if self.is_end in cur_node else False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur_node = self.root
for c in prefix:
if c not in cur_node:
return False
cur_node = cur_node[c]
return True