Implement Trie (Prefix Tree)Total Accepted:
601 Total Submissions:
2396
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Ideas
Using HashMap to save children, use a bool variable to indicate if there is a word ending to this node.
[CODE]
Class Trienode {//Initialize your data structure here. char c; Boolean leaf; Hashmap<character, trienode> children = new Hashmap<character, trienode> (); Public Trienode (char c) {this.c = C; } public Trienode () {};} public class Trie {private Trienode root; Public Trie () {root = new Trienode (); }//Inserts a word into the trie. public void Insert (String word) {map<character, trienode> children = Root.children; for (int i=0; i<word.length (); i++) {char c = word.charat (i); Trienode T; if (Children.containskey (c)) {T = Children.get (c); } else {t = new Trienode (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 boolean search (String word) {Trienode t = Searchnode (Word); return t!=null && t.leaf; }//Returns If there is any word in the trie//that starts with the given prefix. public boolean startsWith (String prefix) {return searchnode (prefix)! = NULL; } private Trienode Searchnode (String word) {map<character, trienode> children = Root.children; Trienode t = null; for (int i=0; i<word.length (); i++) {char c = word.charat (i); if (!children.containskey (c)) return null; t = Children.get (c); children = T.children; } return t; }}//Your Trie object would be instantiated and called as such://Trie Trie = new Trie ();//Trie.insert ("somestring");//TR Ie.search ("key");
Leetcode 208:implement Trie (Prefix Tree)