Implement a trie with insert, search, and startsWith methods.
Note: You may assume that all inputs are consist of lowercase letters a-z.
Trie is efficient in finding all keys with a common prefix and enumerating a dataset of strings in lexicographical order.
Another reason why trie outperforms hash table, is that as hash table increases in size, there are lots of hash collisions and the search time complexity could deteriorate to O(n) where n is the number of keys inserted. Trie could use less space compared to Hash Table when storing many keys with the same prefix. In this case using trie has only O(m) time complexity, where m is the key length. Searching for a key in a balanced tree costs O(mlogn) time complexity.
// Inserts a word into the trie. publicvoidinsert(String word){ if (word != null) { TrieNode cur = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (!cur.containsKey(c)) { cur.put(c, new TrieNode()); } cur = cur.get(c); } cur.setEnd(true); } }
// Returns if the word is in the trie. publicbooleansearch(String word){ if (word == null) returnfalse; TrieNode cur = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (! cur.containsKey(c)) returnfalse; cur = cur.get(c); } return cur.isEnd(); }
// Returns if there is any word in the trie // that starts with the given prefix. publicbooleanstartsWith(String prefix){ if (prefix == null) returnfalse; TrieNode cur = root; for(int i = 0; i < prefix.length(); i++){ char c = prefix.charAt(i); if (! cur.containsKey(c)) returnfalse; cur = cur.get(c); } returntrue; } }
// Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");