Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Building a dictionary Tree
classTrienode {CharC; HashMap<character, trienode> children=NewHashmap<character, trienode>(); BooleanHasword; PublicTrienode () {} PublicTrienode (Charc) { This. c=C; }} Public classtrie{PrivateTrienode Root; PublicTrie () {root=NewTrienode (); } Public voidInsert (String word) {Trienode cur=Root; HashMap<character, trienode> curchildren=Root.children; Char[] wordarray=Word.tochararray (); for(inti=0;i<wordarray.length;i++){ CharWc=Wordarray[i]; if(Curchildren.containskey (WC)) {cur=curchildren.get (WC); }Else{Trienode NewNode=NewTrienode (WC); Curchildren.put (WC, newNode); Cur=NewNode; } Curchildren=Cur.children; if(i==wordarray.length-1) {Cur.hasword=true; } } } Public BooleanSearch (String word) {if(Searchwordnodepos (word) = =NULL){ return false; }Else if(Searchwordnodepos (Word). Hasword) {return true; }Else return false; } Public BooleanstartsWith (String prefix) {if(Searchwordnodepos (prefix) = =NULL){ return false; }Else return true; } PrivateTrienode Searchwordnodepos (String s) {//TODO auto-generated Method StubHashmap<character, trienode> children=Root.children; Trienode cur=NULL; Char[] sarray=S.tochararray (); for(inti=0;i<sarray.length;i++){ CharC=Sarray[i]; if(Children.containskey (c)) {cur=Children.get (c); Children=Cur.children; }Else{ return NULL; } } returncur; } }//Your Trie object would be instantiated and called as such://Trie Trie = new Trie ();//Trie.insert ("somestring");//trie.search ("key");
View Code
Reference: http://blog.csdn.net/yangliuy/article/details/46287671
Http://www.cnblogs.com/huangxincheng/archive/2012/11/25/2788268.html
Leetcode 208Implement Trie (Prefix Tree)