/* ** 树节点类,每个树节点包括 ** next:26个子节点 ** isEnd:当前节点是否为一段字符串结尾 */ classTree{ Tree[] next = new Tree[26]; boolean isEnd = false; }
/** Initialize your data structure here. */ publicTrie(){ this.root = new Tree(); } /** Inserts a word into the trie. */ publicvoidinsert(String word){ temp = root; for (int i = 0; i < word.length(); i++) { id = word.charAt(i) - 'a'; if (temp.next[id] == null) { temp.next[id] = new Tree(); } temp = temp.next[id]; } temp.isEnd = true; } /** Returns if the word is in the trie. */ publicbooleansearch(String word){ temp = root; for (int i = 0; i < word.length(); i++) { id = word.charAt(i) - 'a'; if (temp.next[id] == null) { returnfalse; } temp = temp.next[id]; } return temp.isEnd; } /** Returns if there is any word in the trie that starts with the given prefix. */ publicbooleanstartsWith(String prefix){ temp = root; for (int i = 0; i < prefix.length(); i++) { id = prefix.charAt(i) - 'a'; if (temp.next[id] == null) { returnfalse; } temp = temp.next[id]; } returntrue; } }
/** * 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); */