class Trie {
/** Initialize your data structure here. */privateclassNode{//childs 存放着指向各個孩子結點的指針。
Node[] childs = new Node[26];
boolean isLeaf;
}
private Node root = new Node();
publicTrie() {
}
/** Inserts a word into the trie. */publicvoidinsert(String word) {
insert(word,root);
}
privatevoidinsert(String word,Node node){
if(node == null) return ;
if(word.length() == 0){
node.isLeaf = true;
return ;
}
int index = indexForChar(word.charAt(0));
if(node.childs[index] == null){
node.childs[index] = new Node();
}
insert(word.substring(1),node.childs[index]);
}
privateintindexForChar(char c){
return c - 'a';
}
/** Returns if the word is in the trie. */publicbooleansearch(String word) {
return search(word,root);
}
privatebooleansearch(String word,Node node){
if(node == null) returnfalse;
if(word.length() == 0) return node.isLeaf;
int index = indexForChar(word.charAt(0));
return search(word.substring(1),node.childs[index]);
}
/** Returns if there is any word in the trie that starts with the given prefix. */publicbooleanstartsWith(String prefix) {
return startWith(prefix,root);
}
privatebooleanstartWith(String prefix,Node node){
if(node == null) returnfalse;
if(prefix.length() == 0) returntrue;//注意這裏int index = indexForChar(prefix.charAt(0));
return startWith(prefix.substring(1),node.childs[index]);
}
}
/**
* 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);
*/