LeetCode—208.实现 Trie [前缀树][Implement Trie [Prefix Tree]]——分析及代码[C++、Java]
一、题目
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
提示:
- 1 <= word.length, prefix.length <= 2000
- word 和 prefix 仅由小写英文字母组成
- insert、search 和 startsWith 调用次数 总计 不超过 3 * 10^4 次
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、分析及代码
1. 前缀树
(1)思路
整体构造思路是:树的各节点存储单个字符,对树的深度搜索构成相应字符串。
设计一个节点类,存储子节点的指针及当前位置是否为字符串结尾。
(无需存储字符内容,因为节点的位置本身就对应了字符内容)
(2)代码(C++)
class TrieNode {
public:
bool end_with;//当前位置是否为字符串结尾
TrieNode* next[26];//子节点对应指针
TrieNode() {
end_with = false;
memset(next, 0, sizeof(next));
}
};
class Trie {
TrieNode root;//记录根节点
public:
/** Initialize your data structure here. */
Trie() {}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* node = &root;
for (int i = 0; i <word.size(); i++) {
int c = word[i] - 'a';
if (node->next[c] != NULL) {
node = node->next[c];
}
else {
node->next[c] = new TrieNode();
node = node->next[c];
}
}
node->end_with = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* node = &root;
for (int i = 0; i < word.size(); i++) {
if (node->next[word[i] - 'a'] != NULL)
node = node->next[word[i] - 'a'];
else
return false;
}
return (node->end_with) ? true : false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* node = &root;
for (int i = 0; i < prefix.size(); i++) {
if (node->next[prefix[i] - 'a'] != NULL)
node = node->next[prefix[i] - 'a'];
else
return false;
}
return true;
}
};
(3)结果(C++)
执行用时 :64 ms, 在所有 C++ 提交中击败了 98.95% 的用户;
内存消耗 :44.8 MB, 在所有 C++ 提交中击败了 53.91% 的用户。
(4)代码(Java)
class Trie {
private Trie[] child;//下一字符
private boolean isEnd;//当前字符是否可为终点,区分前缀和完整字符串
/** Initialize your data structure here. */
public Trie() {
this.child = new Trie[26];
this.isEnd = false;
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (node.child[c] == null)
node.child[c] = new Trie();
node = node.child[c];
}
node.isEnd = true;
return;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie node = searchLastNode(word);
return node != null && node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return searchLastNode(prefix) != null;
}
private Trie searchLastNode(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (node.child[c] == null)
return null;
node = node.child[c];
}
return node;
}
}
(5)结果(Java)
执行用时 :41 ms,在所有 Java 提交中击败了 69.36% 的用户;
内存消耗 :48 MB,在所有 Java 提交中击败了 60.38% 的用户。
三、其他
(C++)用 memset 初始化比遍历快不少。