Implement a trie with insert, search, and StartsWith methods.
Note:
You may assume this all inputs is consist of lowercase letters A-Z.
Ideas:
Before also have not contacted Trie, the encyclopedia looked for a bit, is probably the problem of etymology, n word has a public prefix, but the suffix is different, you can use the tree to represent.
can be resolved by recursion.
The code is as follows:
Class Trienode {//should be private; just to reduce the amount of code //Initialize your data structure here. PublicMap<character,trienode> map;//Store suffix Public CharVal//The character value of the current node Public BooleanTail//A string ends with the node Public Trienode() {map =NewHashmap<> (); Tail=false; } Public Trienode(Charc) {map =NewHashmap<> (); This. val=c; Tail=false; }} Public class Trie { PrivateTrienode Root; Public Trie() {root =NewTrienode (); }//Inserts a word into the trie. Public void Insert(String Word) {Insert (Root,word); }Private void Insert(Trienode root,string Word) {if(word.length () = =0) {root.tail=true;return; } Trienode Cur=root;CharC=word.charat (0);if(Cur.map.containsKey (c)) {Trienode child = Cur.map.get (c); Insert (Child,word.substring (1)); }Else{Trienode Child =NewTrienode (c); Cur.map.put (C,child); Insert (Child,word.substring (1)); } }//Returns If the word is in the trie. Public Boolean Search(String Word) {returnSearch (Root,word); }Private Boolean Search(Trienode root,string Word) {if(word.length () = =0)returnroot.tail==true;Charc = Word.charat (0);if(!root.map.containskey (c))return false; Trienode child = Root.map.get (c);returnSearch (Child,word.substring (1)); }//Returns If there is any word in the trie //That starts with the given prefix. Public Boolean StartsWith(String prefix) {returnStartsWith (Root,prefix); }Private Boolean StartsWith(Trienode root,string prefix) {if(prefix.length () = =0)return true;Charc = Prefix.charat (0);if(!root.map.containskey (c))return false; Trienode child = Root.map.get (c);returnStartsWith (Child,prefix.substring (1)); }}//Your Trie object would be instantiated and called as such://Trie Trie = new Trie ();//Trie.insert ("somestring");//Trie.search ("key");
Implement Trie (Prefix Tree)