Topic
Implement Trie
Implement a trie with insert, search, and StartsWith methods.
Sample Example
Note
You may assume this all inputs is consist of lowercase letters A-Z.
Solving
Trie, a dictionary tree, also known as the word search tree, prefix tree, is a hash tree variant. Applied to the statistics and sorting of strings, often by the search engine system for text word frequency statistics.
Properties:
1. The root node does not contain characters, and each node outside the root node contains only one character.
2. From the root node to a node, the characters that pass through the path are concatenated to the string corresponding to that node.
3. All child nodes of each node contain different characters.
The advantage is that the query is fast. For a key with a length of M, the worst-case scenario would be a time of O (m), whereas the BST would require an O (M log n) time.
Program Source Link
1. Understanding the Trie dictionary tree is important
2. Defining the Trienode node class is important
class Trienode { // Initialize your data structure here. Char C; Boolean Leaf; HashMapNew hashmap<character, trienode>(); Public Trienode (char c) { this. c = c; } Public Trienode () {}}
The child node is a form of hashmap that can be quickly taken out of its value.
It's easy to understand the insertion and deletion below.
/*** Your Trie object would be instantiated and called as such: * Trie Trie = new Trie (); * Trie.insert ("Lintcode"); * TR Ie.search ("lint"); would return false * Trie.startswith ("lint"); Would return true*/classTrienode {//Initialize your data structure here. CharC; BooleanLeaf; HashMap<character, trienode> children =NewHashmap<character, trienode>(); PublicTrienode (Charc) { This, cb=C; } PublicTrienode () {}} Public classSolution {PrivateTrienode root =NULL; Publicsolution () {root=NewTrienode (); } //inserts a word into the trie. Public voidInsert (String Word) {Map<Character,TrieNode> children =Root.children; for(inti = 0;i< word.length (); i++){ Charc =Word.charat (i); Trienode T=NULL; if(Children.containskey (c)) {T=Children.get (c); }Else{T=NewTrienode (c); Children.put (c,t); } Children=T.children; if(i = = Word.length ()-1) T.leaf=true; } } //Returns If the word is in the trie. Public BooleanSearch (String word) {Trienode T=Searchnode (word); returnt!=NULL&&t.leaf; } //Returns If there is any word in the trie//That's starts with the given prefix. Public BooleanstartsWith (String prefix) {returnSearchnode (prefix)! =NULL; } Privatetrienode Searchnode (String word) {Map<character,trienode> children =Root.children; Trienode T=NULL; for(inti = 0;i< word.length (); i++){ Charc =Word.charat (i); if(!Children.containskey (c))return NULL; T=Children.get (c); Children=T.children; } returnT; }}Java Code
Total time: 1599 Ms
Lintcode Medium title: Implement Trie