Question
Implement a trie with insert , search , and startsWith methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z .
Solution
A trie node should contains the character, its children and the flag that marks if it's a leaf node.
Trie is an efficient information retrieval data structure. Using trie, search complexities can is brought to optimal limit (key length).
Every node of trie consists of multiple branches. Each branch represents a possible character of keys. We need to mark the last node of every key as leaf node.
We Design Trienode to store 1. Value 2. IsLeaf 3. A map of children (map is used for quick selection)
In this "we can implement Trie start from root. ADD new child to original parent was implemented by put action in map.
Note here, search and startsWith differs.
Null
|
A
|
B
For "A", search would return false, while StartsWith would return true.
1 classTrienode {2 Public Charvalue;3 Public Booleanisleaf;4 PublicHashmap<character, trienode>children;5 6 //Initialize your data structure here.7 PublicTrienode (Charc) {8Value =C;9Children =NewHashmap<character, trienode>();Ten } One } A - Public classTrie { - Trienode Root; the - PublicTrie () { -Root =NewTrienode ('! ')); - } + - //inserts a word into the trie. + Public voidInsert (String word) { A Char[] Wordarray =Word.tochararray (); atTrienode CurrentNode =Root; - - for(inti = 0; i < wordarray.length; i++) { - Charc =Wordarray[i]; -Hashmap<character, trienode> children =Currentnode.children; - trienode node; in if(Children.containskey (c)) { -node =Children.get (c); to}Else { +node =NewTrienode (c); - Children.put (c, node); the } *CurrentNode =node; $ Panax Notoginseng if(i = = Wordarray.length-1) -Currentnode.isleaf =true; the } + A } the + //Returns If the word is in the trie. - Public BooleanSearch (String word) { $Trienode CurrentNode =Root; $ for(inti = 0; I < word.length (); i++) { - Charc =Word.charat (i); -Hashmap<character, trienode> children =Currentnode.children; the if(Children.containskey (c)) { -Trienode node =Children.get (c);WuyiCurrentNode =node; the //need to check whether it ' s leaf node - if(i = = Word.length ()-1 &&!node.isleaf) Wu return false; -}Else { About return false; $ } - } - return true; - } A + //Returns If there is any word in the trie the //That's starts with the given prefix. - Public BooleanstartsWith (String prefix) { $Trienode CurrentNode =Root; the for(inti = 0; I < prefix.length (); i++) { the Charc =Prefix.charat (i); theHashmap<character, trienode> children =Currentnode.children; the if(Children.containskey (c)) { -Trienode node =Children.get (c); inCurrentNode =node; the}Else { the return false; About } 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");
Implement Trie (Prefix Tree) solution