Implement Trie (Prefix Tree)
Problem
A prefix tree (also known as a trie) is a tree data structure used to efficiently store and retrieve keys in a set of strings. Some applications of this data structure include auto-complete and spell checker systems.
Implement the PrefixTree class:
PrefixTree()Initializes the prefix tree object.void insert(String word)Inserts the stringwordinto the prefix tree.boolean search(String word)Returnstrueif the stringwordis in the prefix tree (i.e., was inserted before), andfalseotherwise.boolean startsWith(String prefix)Returnstrueif there is a previously inserted stringwordthat has the prefixprefix, andfalseotherwise.
Examples
Example 1:
Input: ["Trie", "insert", "dog", "search", "dog", "search", "do", "startsWith", "do", "insert", "do", "search", "do"]
Output: [null, null, true, false, true, null, true]
Explanation:
PrefixTree prefixTree = new PrefixTree(); prefixTree.insert("dog"); prefixTree.search("dog"); // return true prefixTree.search("do"); // return false prefixTree.startsWith("do"); // return true prefixTree.insert("do"); prefixTree.search("do"); // return true
Constraints
1 <= word.length, prefix.length <= 1000wordandprefixare made up of lowercase English letters.
Solution
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate