/** 208. Implement Trie (Prefix Tree) * 2016-6-9 by Mingyang * I use the hashmap to make the map here, with an array, the same principle * but I did not think of the need for a isend propert Y, because search here has to find the end of the time is the only successful find*/classTries { PublicTrienode Root; PublicTries () {root=NewTrienode (); Root.isend=true; } Public voidInsert (String word) {if(Word = =NULL|| Word.length () = = 0) return; Trienode node=Root; Char[] Letters =Word.tochararray (); for(inti = 0; I < word.length (); i++) { intpos = letters[i]-' a '; if(Node.son[pos] = =NULL) {Node.son[pos]=NewTrienode (); Node.son[pos].val=Letters[i]; } node=Node.son[pos]; } node.isend=true; } //Returns If the word is in the trie. Public BooleanSearch (String word) {if(Word = =NULL|| Word.length () = = 0) { return false; } trienode Node=Root; Char[] Letters =Word.tochararray (); for(inti = 0; I < word.length (); i++) { intpos = letters[i]-' a '; if(Node.son[pos]! =NULL) {node=Node.son[pos]; } Else { return false; } } returnNode.isend; } //Returns If there is any word in the trie//That's starts with the given prefix. Public BooleanstartsWith (String prefix) {if(prefix = =NULL|| Prefix.length () = = 0) { return false; } trienode Node=Root; Char[] Letters =Prefix.tochararray (); for(inti = 0; I < prefix.length (); i++) { intpos = letters[i]-' a '; if(Node.son[pos]! =NULL) {node=Node.son[pos]; } Else { return false; } } return true; }}classTrienode {//Initialize your data structure here.Trienode[] Son;//all the sons of the node BooleanIsend;//Is not the last node CharVal//the value of the nodeTrienode () { This. son =NewTrienode[26]; This. Isend =false; }}
208. Implement Trie (Prefix Tree)