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. */// 沒則插,結尾改 true (出現了,但是沒真正 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];}// 結束,標志單詞結尾字符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);*/
更新版
其實三個函數的代碼都差不多= =
前綴樹:存儲字符串的一種樹結構(二十六叉樹),可以實現拼寫檢查、自動補全功能。
classTrie{TrieNode root;privateclassTrieNode{boolean isEnd;TrieNode[] nextNode;publicTrieNode(){isEnd =false;nextNode =newTrieNode[26];}}publicTrie(){root =newTrieNode();}publicvoidinsert(String word){TrieNode nowNode = root;for(char c : word.toCharArray()){int index = c -'a';if(nowNode.nextNode[index]==null){nowNode.nextNode[index]=newTrieNode();}nowNode = nowNode.nextNode[index];}nowNode.isEnd =true;}publicbooleansearch(String word){TrieNode nowNode = root;for(char c : word.toCharArray()){int index = c -'a';if(nowNode.nextNode[index]==null){returnfalse;}nowNode = nowNode.nextNode[index];}return nowNode.isEnd;}publicbooleanstartsWith(String prefix){TrieNode nowNode = root;for(char c : prefix.toCharArray()){int index = c -'a';if(nowNode.nextNode[index]==null){returnfalse;}nowNode = nowNode.nextNode[index];}returntrue;}}