895. Prefix Tree
A harbour office keeps a registry of vessel names typed one at a time, and clerks need instant look-ups. Build the class PrefixTree with an empty constructor.
insert(word)stores the lowercasewordin the registry. Storing a name that is already present changes nothing.search(word)returnstrueonly if exactly thiswordwas inserted before.startsWith(prefix)returnstrueif at least one inserted word begins withprefix(a word counts as a prefix of itself).
Each call must cost time proportional to the length of its argument, not to the number of stored words.
Example 1
- Input:
- operations = ["PrefixTree","insert","search","startsWith","insert","search"]arguments = [[],["quartz"],["quart"],["quart"],["quart"],["quart"]]
- Output:
- [null,null,false,true,null,true]
- Explanation:
Only
quartzis stored at first, soquartis a prefix but not a stored word; after inserting it, it is found.
Example 2
- Input:
- operations = ["PrefixTree","insert","search","startsWith","startsWith"]arguments = [[],["nebula"],["nebulae"],["nebulae"],["n"]]
- Output:
- [null,null,false,false,true]
- Explanation:
A longer string than any stored word is never found, while the single letter
nstartsnebula.
Constraints
1 ≤ word.length, prefix.length ≤ 50
All strings consist of lowercase English letters.
At most 2000 calls in total.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(L) per call
- Space
- O(total inserted characters)