The original title link is here: https://leetcode.com/problems/implement-trie-prefix-tree/
Trie is a data structure used to make dictionary lookups, which is a multi-fork number structure for fast retrieval. For example, the dictionary tree of the English alphabet is 26 forks, and the number of the dictionary tree is a 10-fork tree.
The basic properties of the trie tree are three points, which are summarized as:
- The root node does not contain characters, and each node outside the root node contains only one character.
- From the root node to a node, the characters that pass through the path are concatenated to the corresponding string for that node.
- All child nodes of each node contain different strings.
Note:search () and StartsWith () are different, and search also needs to be aware of whether the leaf node of the trie tree has been hit when jumping out of the loop.
AC Java:
1 classTrienode {2 //Mark If this node is the end of the word3 Booleanisleaf;4Hashmap<character,trienode>nexts;5 PublicTrienode () {6Nexts =NewHashmap<character,trienode>();7 }8 }9 Ten Public classTrie { One PrivateTrienode Root; A - PublicTrie () { -Root =NewTrienode (); the } - - //inserts a word into the trie. - Public voidInsert (String word) { +Trienode p =Root; - Char[] s =Word.tochararray (); + intLen =s.length; A inti = 0; at //traverse the existing character - while(i<Len) { - if(P.nexts.containskey (S[i])) { -p =P.nexts.get (S[i]); -i++; -}Else{ in Break; - } to } + //Append New Nodes - while(i<Len) { theTrienode NewNode =NewTrienode (); * P.nexts.put (s[i],newnode); $p =NewNode;Panax Notoginsengi++; - } the //Set the end of the word +P.isleaf =true; A } the + //Returns If the word is in the trie. - Public BooleanSearch (String word) { $Trienode p =Root; $ Char[] s =Word.tochararray (); - intLen =s.length; - inti = 0; the while(i<Len) { -Trienode NextNode =P.nexts.get (S[i]);Wuyi if(NextNode = =NULL){ the return false; - } Wup =NextNode; -i++; About } $ //return If this is a leaf node - returnp.isleaf; - } - A //Returns If there is any word in the trie + //That's starts with the given prefix. the Public BooleanstartsWith (String prefix) { -Trienode p =Root; $ Char[] s =Prefix.tochararray (); the intLen =s.length; the inti = 0; the while(i<Len) { theTrienode NextNode =P.nexts.get (S[i]); - if(NextNode = =NULL){ in return false; the } thep =NextNode; Abouti++; the } the return true; the } + } - the //Your Trie object would be instantiated and called as such:Bayi //Trie Trie = new Trie (); the //Trie.insert ("somestring"); the //trie.search ("key");
Reference this post: Http://blog.csdn.net/wzy_1988/article/details/45744067#trie Tree Basic implementation
Leetcode Implement Trie (Prefix Tree)