思路:定义前缀树节点,属性有结束标志位isEnd,下一个前缀树节点。定义根节点root,添加、查找时都从根节点开始搜索。
class Trie {
class TrieNode{
private boolean isEnd;
private TrieNode[] next;
public TrieNode(){
isEnd=false;
next=new TrieNode[26];
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root=new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node=root;
for(char c:word.toCharArray()){
if(node.next[c-'a']==null){
node.next[c-'a']=new TrieNode();
}
node=node.next[c-'a'];
}
node.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node=root;
for(char c:word.toCharArray()){
if(node.next[c-'a']==null){
return false;
}
node=node.next[c-'a'];
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node=root;
for(char c:prefix.toCharArray()){
if(node.next[c-'a']==null){
return false;
}
node=node.next[c-'a'];
}
return true;
}
}