Implements the Trie tree, which can be used as an implementation dictionary. It can be used to store, find, and delete strings, while implementing the ability to return all the results of a specified character with a prefix.
Each node saves all child nodes and maps that correspond to the characters on the path, using count to record how much word is present in each node's sub-tree, and to facilitate the removal of the operation.
Findallwithprefix used the idea of Dfs, traversing all prefixed results and outputting. Commonly used in search engines.
1 classTrienode {2 intcount;3Map<character, trienode>children;4 BooleanIsword;5 PublicTrienode () {6Count=0;7isword=false;8children=NewHashmap<character,trienode>();9 }Ten } One A Public classMytrie { - Trienode Root; - the PublicMytrie () { -Root =NewTrienode (); - } - + Public BooleanSearch (String s) { - if( This. root = =NULL|| s = =NULL|| S.length () = = 0) { + return false; A } atTrienode cur=Root; - for(inti = 0; I < s.length (); i++) { -Trienode next=Cur.children.get (S.charat (i)); - if(Next = =NULL) { - return false; - } inCur=Next; - } to returnCur.isword; + } - Public voidInsert (String s) { the if(Search (s) | | s = =NULL|| S.length () = = 0) { * return; $ }Panax NotoginsengTrienode cur=Root; - for(inti = 0; I < s.length (); i++) { theTrienode next=Cur.children.get (S.charat (i)); + if(Next = =NULL) { Anext=NewTrienode (); the Cur.children.put (S.charat (i), next); + } -Cur=Next; $cur.count++; $ } -cur.isword=true; - } the Public BooleanDelete (String s) { - if(!search (s)) {Wuyi return false; the } -Trienode cur=Root; Wu for(inti=0; I<s.length (); i++) { -Trienode next=Cur.children.get (S.charat (i)); About if(Next.count = = 1) { $ Cur.children.remove (S.charat (i)); - return true; - } -next.count--; ACur=Next; + } thecur.isword=false; - return true; $ } the the PublicList<string>Findallwithprefix (String s) { theTrienode matchnode=Searchnode (s); the if(Matchnode = =NULL) { - return NULL; in } thelist<string>result=NewArraylist<string>(); theDFS (result, Matchnode,NewStringBuilder (s)); About returnresult; the } the Private voidDFS (list<string>result, Trienode Matchnode, StringBuilder SB) { the if(Matchnode.isword = =true) { + Result.add (sb.tostring ()); - } the for(Map.entry<character, trienode>Child:matchNode.children.entrySet ()) {Bayi Sb.append (Child.getkey ()); the DFS (Result,child.getvalue (), SB); theSb.deletecharat (Sb.length ()-1); - } - } the PrivateTrienode Searchnode (String s) { the if(s = =NULL|| S.length () = = 0) { the return NULL; the } -Trienode cur=Root; the for(inti=0; I<s.length (); i++) { theTrienode next=Cur.children.get (S.charat (i)); the if(Next = =NULL) {94 returncur; the } theCur=Next; the }98 returncur; About } -}
Java Trie (dictionary tree) implementation