Topic:
Implement a trie with insert
, search
, and startsWith
methods.
Your Trie object would be instantiated and called as such:
Trie Trie = new Trie ();
Trie.insert ("somestring");
Trie.search ("key");
Ideas:
The title of the topic is to implement a prefix tree, which is used to store string, so it can be understood as a 26-fork tree, in order to save each node of the child, with HashMap to store.
Also review the concept of the prefix tree, in addition to the content of a character, each node should also have a flag bit, whether it is already checked (that is, added) words.
Insert: Parses every character of a word, if present with a child that is already there, then loops to the child node, otherwise creates a new child node, and finally the character at the end of the word Isword the flag bit true;
Search: Parse each character one by one, or return FALSE if the child does not exist, or, after the loop, look at the flag of the trailing character;
Pifix: As with search, it returns true only at the end of the child map where each character is present.
Code:
classTrienode {//Initialize your data structure here. BooleanIsword; HashMap<character, trienode>map; PublicTrienode () {map=NewHashmap<character, trienode>(); }} Public classTrie {PrivateTrienode Root; PublicTrie () {root=NewTrienode (); } //inserts a word into the trie. Public voidInsert (String word) {Char[] Charray =Word.tochararray (); Trienode Temp=Root; for(inti = 0; i < charray.length; i++){ if(!Temp.map.containsKey (Charray[i]) temp.map.put (Charray[i],NewTrienode ());//Addtemp = Temp.map.get (Charray[i]);//go to child node if(i = = charray.length-1)//End CharacterTemp.isword =true; } } //Returns If the word is in the trie. Public BooleanSearch (String word) {Trienode temp=Root; for(inti = 0; I < word.length (); i++) {Trienode next=Temp.map.get (Word.charat (i)); if(Next = =NULL) return false; Temp=Next; } returnTemp.isword; } //Returns If there is any word in the trie//That's starts with the given prefix. Public BooleanstartsWith (String prefix) {Trienode temp=Root; for(inti = 0; I < prefix.length (); i++) {Trienode next=Temp.map.get (Prefix.charat (i)); if(Next = =NULL) return false; Temp=Next; } return true; }}
Reference Link: http://www.bubuko.com/infodetail-807921.html
[Leetcode-java] Implement Trie (Prefix Tree)