原题链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/submissions/。
构建前缀树/字典树。下面我们学习一下字典树。
令S为一个来自字母表
∑
\sum
∑的s个字符的集合。S的标准字典树是一个具有以下特性的有序数T.
- 除了根之外的T的每个节点,都用 ∑ \sum ∑中的字符做标签。
- T的内部节点的孩子节点有不同的标签
- T的s个叶子节点,每一个叶子节点和S中的一个字符串相连,从根到T的一个叶子节点f的路径的标签串联产生了一个在S中的字符串。
下面用一个例子来说明什么是字典树。
上图是一个字符串 { b e a r , b e l l , b i d , b u l l , b u y , s e l l , s t o c k , s t o p } \{ bear, bell, bid, bull, buy, sell, stock, stop\} {bear,bell,bid,bull,buy,sell,stock,stop}的标准字典树。
下图是生成字典树的python程序:
from collections import defaultdict
class TrieNode: # 字典树的节点类
def __init__(self):
self.children = defaultdict(TrieNode) # 孩子节点是值为列表的字典
self.is_word = False # 如果是叶子节点,那么这个值应该为True。代表了是字符串集中的一个字符串。
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode() # 根节点
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.root
for char in word:
cur = cur.children[char]
cur.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
cur = self.root
for char in word:
cur = cur.children.get(char)
if not cur:
return False
return cur.is_word
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur = self.root
for char in prefix:
cur = cur.children.get(char)
if not cur:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
不使用collection中defaultdict模块速度会更快。
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
self.is_word = -1
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
cur = self.root
for char in word:
if char not in cur:
cur[char] = {}
cur = cur[char]
cur[self.is_word] = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
cur = self.root
for char in word:
if char not in cur:
return False
cur = cur[char]
if self.is_word not in cur:
return False
return True
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
cur = self.root
for char in prefix:
if char not in cur:
return False
cur = cur[char]
return True