仅供自己学习记录
LeetCode刷题日记2021-4-14
题目描述
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
- Trie() 初始化前缀树对象。
- void insert(String word) 向前缀树中插入字符串 word 。
- boolean search(String word) 如果字符串 word 在前缀树中,返回true(即,在检索之前已经插入);否则,返回 false 。
- boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回true;否则,返回 false 。
示例:
输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]
解释
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
题解思路:
前缀树
(只保存小写字符的)「前缀树」是一种特殊的多叉树,它的 TrieNode 中 chidren 是一个大小为 26 的一维数组,分别对应了26个英文字符 ‘a’ ~ ‘z’,也就是说形成了一棵 26叉树。
前缀树的结构可以定义为下面这样。
里面存储了两个信息:
-
isWord 表示从根节点到当前节点为止,该路径是否形成了一个有效的字符串。
-
children 是该节点的所有子节点。
class TrieNode { public: vector<TrieNode*> children; bool isWord; TrieNode() : isWord(false), children(26, nullptr) { } ~TrieNode() { for (auto& c : children) delete c; } };
在构建前缀树的时候,按照下面的方法:
- 根节点不保存任何信息;
- 关键词放到「前缀树」时,需要把它拆成各个字符,每个字符按照其在 ‘a’ ~ ‘z’ 的序号,放在对应的 chidren里面。下一个字符是当前字符的子节点。
- 一个输入字符串构建「前缀树」结束的时候,需要把该节点的 isWord 标记为 true,说明从根节点到当前节点的路径,构成了一个关键词。
下面是一棵「前缀树」,其中保存了 {“am”, “an”, “as”, “b”, “c”, “cv”} 这些关键词。图中红色表示 isWord 为 true。
看下面这个图的时候需要注意:
- 所有以相同字符开头的字符串,会聚合到同一个子树上。比如 {“am”, “an”, “as”} ;
- 并不一定是到达叶子节点才形成了一个关键词,只要 isWord 为true,那么从根节点到当前节点的路径就是关键词。比如 {“c”,“cv”} ;
题解代码
定义前缀树节点类型
class Node(object):
def __int__(self):
self.children=collections.default(Node)
self.isWord=False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root=Node()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
current=self.root
for i in word:
current=current.children[i]
current.isWord=True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
current=self.root
for i in word:
current=current.children.get(i)
if current==None:
return False
return current.isWord
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
current=self.root
for i in prefix:
current=current.children.get(i)
if current is None:
return False
return True
来源
https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/fu-xue-ming-zhu-cong-er-cha-shu-shuo-qi-628gs/