题目描述
➡ 题目链接 ⬅
实现一个 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
说明:
- 你可以假设所有的输入都是由小写字母 a-z 构成的。
- 保证所有输入均为非空字符串。
解题思路
- Trie是一种树形数据结构,常用于检索字符串数据集中的键。其结点结构如下:
- 假设字符只有小写字母,共26个,则最多有26个指向子结点的链接(树中每个结点最多有26个儿子),其中每一个链接对应一个字母。
- python中使用字典
dic
构建Trie树数据结构。
- 插入操作
- 首先从Trie树的根节点开始搜索,遍历
word
每一个字符,分为两种情况:
- 若字典
dic
存在word的第一个字符,则沿着该链接移动到树的下一层,即tree = tree[i]
,继续搜索word
的下一个字符,直到结束。 - 若字典
dic
不存在word
的第一个字符,则创建一个新的节点,并将它与父节点相链接。 - 重复1,2步骤,直到插入
word
的最后一个字符,再存入结束标志符'#'
,算法完成。
- 首先从Trie树的根节点开始搜索,遍历
- 查找操作
- 从
word
的第一个字符开始查找,分为两种情况:
- 若查找成功,则沿着该链接移动到树的下一层,并继续查找下一个字符。
- 若查找失败,判断当前节点是否为
'#'
,若是,则返回True
;否则,返回False
。
- 从
- 查找前缀操作
- 该方法与查找操作类似。
- 从根节点开始遍历,直到前缀
prefix
的最后一个字符。若能够顺利达到prefix
的尾部,则返回True
;若prefix
的某一个字符查找失败,则返回False
。
代码
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
tree = self.dic
for i in word:
tree = tree.setdefault(i, {})
tree['#'] = '#'
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
tree = self.dic
for i in word:
if i not in tree:
return False
tree = tree[i]
return '#' in tree
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
tree = self.dic
for i in prefix:
if i not in tree:
return False
tree = tree[i]
return True
时间复杂度
- 时间复杂度优化至树的高度,即时间复杂度为O(m)