思路:
主要是插入和搜索的代码繁琐
代码:
class Trie {
private Trie[] children;
private boolean isEnd;
/** Initialize your data structure here. */
public Trie() {
children=new Trie[26];
isEnd=false;
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie node=this;
for(int i=0;i<word.length();i++){
char c=word.charAt(i);
int index=c-'a';
if(node.children[index]==null){
node.children[index]=new Trie();
}
node=node.children[index];
}
node.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie node=searchPrefix(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 searchPrefix(prefix)!=null;
}
private Trie searchPrefix(String prefix){
Trie node=this;
for(int i=0;i<prefix.length();i++){
char c=prefix.charAt(i);
int index=c-'a';
if(node.children[index]==null){
//这里是与插入的不同之处
//插入这里是新建一个node,而这里直接返回null
return null;
}
node=node.children[index];
}
return node;
}
}
分解:
1)核心代码:
i)insert:
Trie node=this;
for(int i=0;i<word.length();i++){
char c=word.charAt(i);
int index=c-'a';
if(node.children[index]==null){
node.children[index]=new Trie();
}
node=node.children[index];
}
node.isEnd=true;
ii)searchPrefix:
Trie node=this;
for(int i=0;i<prefix.length();i++){
char c=prefix.charAt(i);
int index=c-'a';
if(node.children[index]==null){
//这里是与插入的不同之处
//插入这里是新建一个node,而这里直接返回null
return null;
}
node=node.children[index];
}
return node;
插入和搜索的核心代码的区别是:
插入这里是新建一个node,而这里直接返回null
if(node.children[index]==null){
return null;
}
2)注意children的类型是Trie[]而不是int[]
Trie[] children=new Trie[26];