Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
字典树实现:
public class Trie {
Node root;
/** Initialize your data structure here. */
public Trie() {
root=new Node();
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node temp=root;
for(int i=0;i<word.length();i++){
char ch=word.charAt(i);
if(temp.childs[ch-'a']==null){
temp.childs[ch-'a']=new Node();
}
temp=temp.childs[ch-'a'];
}
temp.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Node temp=root;
for(int i=0;i<word.length();i++){
int index=word.charAt(i)-'a';
if(temp.childs[index]==null) return false;
temp=temp.childs[index];
}
return temp.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Node temp=root;
for(int i=0;i<prefix.length();i++){
int index=prefix.charAt(i)-'a';
if(temp.childs[index]==null) return false;
temp=temp.childs[index];
}
return true;
}
class Node{
Node[] childs;
boolean isEnd;
public Node() {
childs = new Node[26];
}
}
}
/**
* 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);
*/