请你实现 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
class TreeNode{
TreeNode[] children;
boolean isEnd;
public TreeNode(){
isEnd=false;
children=new TreeNode[26];
}
}
class Trie {
TreeNode root;//根节点不存储 从他的子节点开始存
public Trie() {
root=new TreeNode();
}
public void insert(String word) {
TreeNode cur=root;
for(int i=0;i<word.length();i++){
int index=word.charAt(i)-'a';
if(cur.children[index]==null){
cur.children[index]=new TreeNode();
cur.children[index].isEnd=false;
}
cur=cur.children[index];
}
cur.isEnd=true;
}
public boolean search(String word) {
TreeNode cur=find(word);
return cur!=null&&cur.isEnd==true;
}
public boolean startsWith(String prefix) {
TreeNode cur=find(prefix);
return cur!=null;
}
public TreeNode find(String word){
TreeNode cur=root;
for(int i=0;i<word.length();i++){
int index=word.charAt(i)-'a';
if(cur.children[index]==null){
return null;
}
cur=cur.children[index];
}
return cur;
}
}