问:请你实现 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]
原题链接:https://leetcode.cn/problems/implement-trie-prefix-tree/
答:
class Trie {
private boolean flag;//定义一个boolean类型来判断是否是单词的末尾
private Trie[] children;//指向子节点的指针数组
/** Initialize your data structure here. */
public Trie() {
children = new Trie[26];//26个节点代表26个小写字母 a-z
flag = false;//默认flag是false
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie node = this;
for(int i = 0;i < word.length();i++)
{
int index = word.charAt(i) - 'a';//单词都是a-z
if(node.children[index] == null)//如果没有这个子节点的话就新建一个子节点
{
node.children[index] = new Trie();
}
node = node.children[index];//如果有就插入
}
node.flag = true;//循环结束,整个单词插入完成
}
/** Returns if the word is in the trie. */
public boolean search(String word) {//函数返回boolean类型,所以再重新定义一个函数作为调用
Trie node = search1(word);
if(node != null && node.flag == true )//如果节点不是null并且单词已经到末尾
return true;
else
return false;
}
public Trie search1(String word)
{
Trie node = this;
for(int i = 0;i < word.length();i++)
{
int index = word.charAt(i) - 'a';
if(node.children[index] == null)
{
return null;//如果没有查找返回null
}
node = node.children[index];
}
return node;//找到就返回
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if(search1(prefix)!=null)
return true;
else
return false;
}
}
/**
* 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);
*/
解析都在代码注释里了,有什么不明白的可以评论一起交流学习~