class Trie {
private boolean is_string = false;
private Trie[] next = new Trie[26];
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie root = this;
char w[] = word.toCharArray();
for(int i = 0;i<w.length;++i){
if(root.next[w[i]-'a'] == null){
root.next[w[i] - 'a'] = new Trie();
}
root = root.next[w[i]- 'a'];
}
root.is_string = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie root = this;
char w[] = word.toCharArray();
for(int i = 0 ;i<w.length;++i){
if(root.next[w[i] - 'a']==null){
return false;
}
root =root.next[w[i]-'a'];
}
return root.is_string;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie root = this;
char w[]= prefix.toCharArray();
for(int i = 0;i<w.length;++i){
if(root.next[w[i] - 'a'] ==null){
return false;
}
root = root.next[w[i] - 'a'];
}
return true;
}
}
/**
* 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);
*/
学到很多。
特别是boolean is_String 判断是不是字符的结尾。
一开始加入apple,只有这个e这个节点 布尔值是true的;
所以search(app) 返回的false