classTrie{privateclassTrieNode{boolean isEnd;TrieNode[] next;TrieNode(){isEnd =false;next =newTrieNode[26];}}privateTrieNode root;/** Initialize your data structure here. */publicTrie(){root =newTrieNode();}/** Inserts a word into the trie. */// 沒則插,結(jié)尾改 true (出現(xiàn)了,但是沒真正 insert 的話,不算:比如 insert apple , 然后 search app = falsepublicvoidinsert(String word){char[] wordC = word.toCharArray();TrieNode nowNode = root;for(int i =0; i < wordC.length; i++){// error:TrieNode nextNode = nowNode.next[wordC[i] - 'a']; nextNode = new TrieNode()// 會直接丟失引用!int index = wordC[i]-'a';if(nowNode.next[index]==null){nowNode.next[index]=newTrieNode();}nowNode = nowNode.next[index];}// 結(jié)束,標志單詞結(jié)尾字符nowNode.isEnd =true;}/** Returns if the word is in the trie. */publicbooleansearch(String word){char[] wordC = word.toCharArray();TrieNode nowNode = root;for(int i =0; i < wordC.length; i++){int index = wordC[i]-'a';if(nowNode.next[index]==null){returnfalse;}nowNode = nowNode.next[index];}return nowNode.isEnd;}/** Returns if there is any word in the trie that starts with the given prefix. */publicbooleanstartsWith(String prefix){char[] wordC = prefix.toCharArray();TrieNode nowNode = root;for(int i =0; i < wordC.length; i++){int index = wordC[i]-'a';if(nowNode.next[index]==null){returnfalse;}nowNode = nowNode.next[index];}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);*/