题目描述
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
示例1
输入
inputs = [“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
inputs = [[], [“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
思路
先思考字典树每个结点的数据结构如何设计。
因为只有26个字母,所以我们可以用大小为26的数组来表示当前结点的子节点,数组中元素的类型也是结点的数据结构(因为它指向子节点)。
同时还要设一个布尔变量来判断当前结点是不是单词的结尾,因为字典树中单词的结尾不一定位于叶子结点。比如字典树中有apple和app两个单词,那么app的最后一个p就不是叶子结点,为了能知道有app这个单词,我们就需要在最后一个p的结点中将他的布尔变量置为true。
那么初始化字典树的代码就如下:
class Trie {
private TreeNode root;
class TreeNode{
TreeNode[] children;
boolean isWord;
public TreeNode(){
children = new TreeNode[26];
}
}
/** Initialize your data structure here. */
public Trie() {
root = new TreeNode();
}
}
insert函数:
首先设置一个当前指针node指向root结点。然后我们依次遍历要插入单词的每个字母,如果存在的话,直接将当前指针指向对应的子节点,如果不存在就new一个然后指向它。最后不要忘了将最后一个结点的isWord置为true。
search函数:
同样遍历单词的每个字母,如果不存在直接返回false,如果存在就指向对应子节点。最后不要忘了判断最后一个字母的isWord是不是true,只有是true才能表明字典树中有这个单词。
startsWith函数:
和search函数几乎一样,只是最后不用判断isWord。
完整代码
class Trie {
private TreeNode root;
class TreeNode{
TreeNode[] children;
boolean isWord;
public TreeNode(){
children = new TreeNode[26];
}
}
/** Initialize your data structure here. */
public Trie() {
root = new TreeNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TreeNode node = root;
for(char ch : word.toCharArray()){
if(node.children[ch - 'a'] == null){
node.children[ch - 'a'] = new TreeNode();
}
node = node.children[ch - 'a'];
}
node.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TreeNode node = root;
for(char ch : word.toCharArray()){
if(node.children[ch - 'a'] == null){
return false;
}
node = node.children[ch - 'a'];
}
return node.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TreeNode node = root;
for(char ch : prefix.toCharArray()){
if(node.children[ch - 'a'] == null){
return false;
}
node = node.children[ch - '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);
*/