Topic:
Implement a trie with insert , search , and startsWith methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z .
test instructions and analysis: implement a dictionary tree or prefix tree to insert, delete and startswith judgment. This defines a Trienode class as the node class for the dictionary tree. Then there is a Chilrden array to save the child nodes, a Isword variable to determine whether the node from the root node is a word. Here I use an array of length 26 to save the child nodes, waste some memory, or use a hashmap to implement.
Code:
classtrienode{ Public CharWord; BooleanIsword;//whether the record is the end of a word Publictrienode[] ChildNodes =NewTrienode[26]; PublicTrienode () {}; PublicTrienode (Charc) {trienode node=NewTrienode (); Node.word=C; }} Public classTrie {PrivateTrienode Root; /**Initialize your data structure here.*/ PublicTrie () {root=NewTrienode (); Root.word= ' '; } /**inserts a word into the trie.*/ Public voidInsert (String Word) {trienode node=Root; for(intI=0;i<word.length (); i++){ if(Node.childnodes[(Word.charat (i)-' a ')]!=NULL) {node= node.childnodes[(Word.charat (i)-' a ')]; }Else{//need to re-create later for(intJ=i;j<word.length (); j + +) {//re-create a sub-treeNode.childnodes[(Word.charat (j)-' a ')] =NewTrienode (Word.charat (j)); Node= Node.childnodes[(Word.charat (j)-' a ')]; } Break;//Jump out of the loop}} Node.isword=true; } /**Returns If the word is in the trie.*/ Public BooleanSearch (String word) {//To the root node can be judged, the middle is not countedTrienode node =Root; for(intI=0;i<word.length (); i++) { if(Node.childnodes[(Word.charat (i)-' a ')]! =NULL) {node= node.childnodes[(Word.charat (i)-' a ')]; }Else { return false; } } returnNode.isword; } /**Returns If there is any word in the trie that starts with the given prefix.*/ Public BooleanstartsWith (String prefix) {trienode node=Root; for(intI=0;i<prefix.length (); i++) { if(Node.childnodes[(Prefix.charat (i)-' a ')]! =NULL) {node= node.childnodes[(Prefix.charat (i)-' a ')]; }Else { return false; } } return true; }}/*** Your Trie object would be instantiated and called as such: * Trie obj = new Trie (); * Obj.insert (Word); * Boolean PA Ram_2 = Obj.search (word); * Boolean param_3 = obj.startswith (prefix); */
[Leetcode] 208. Implement Trie (Prefix Tree) Java