题目描述:
题目链接:leetcode 208. 实现 Trie
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 3 * 10^{4} 3∗104 次
Java代码:
//定义一个trie的结点类TrieNode,其成员变量有一个布尔型的isWord及TrieNode型的数组,相当于一个多叉树
//isWord为true时表示该结点是一个单词的结尾
//TrieNode型的数组用于指向其它代表字母的TrieNode结点
class TrieNode {
boolean isWord;
TrieNode[] next;
TrieNode() {
isWord = false;
next = new TrieNode[26];
}
}
class Trie {
/**
* Initialize your data structure here.
*/
TrieNode root; //一个根结点代表了一棵trie树(前缀树),根节点并不存储任何字母
public Trie() {
root = new TrieNode();
}
/**
* Inserts a word into the trie.
*/
//遍历word的每个字母,若之前未在当前结点插入当前字母,就申请一个TrieNode结点,然后像建链表一样往下加结点。
public void insert(String word) {
TrieNode pr = this.root;
int n = word.length();
for (int i = 0; i < n; i++) {
char c = word.charAt(i);
if (pr.next[c - 'a'] == null) {
TrieNode node = new TrieNode();
pr.next[c - 'a'] = node;
}
pr = pr.next[c - 'a'];
}
pr.isWord = true; //末尾的单词做一个标记
}
/**
* Returns if the word is in the trie.
*/
//和建Trie类似,如果还未创建Trie中的某个结点或者末尾结点不是单词的结尾则表示没有这个word
public boolean search(String word) {
TrieNode pr = this.root;
int n = word.length();
for (int i = 0; i < n; i++) {
char c = word.charAt(i);
if (pr.next[c - 'a'] == null) return false;
pr = pr.next[c - 'a'];
}
return pr.isWord;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
//查前缀和查单词的区别仅在于查前缀只要之前创建了结点就存在前缀,而单词一定要满足最后一个字母对应结点的isWord为true
public boolean startsWith(String prefix) {
TrieNode pr = this.root;
int n = prefix.length();
for (int i = 0; i < n; i++) {
char c = prefix.charAt(i);
if (pr.next[c - 'a'] == null) return false;
pr = pr.next[c - 'a'];
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/