Typeahead
Description
Implement typeahead. Given a string and a dictionary, return all words that contains the string as a substring. The dictionary will give at the initialize method and wont be changed. The method to find all words with given substring would be called multiple times.
Example
Given dictionary ={"Jason Zhang", "James Yu", "Bob Zhang", "Larry Shi"}
search"Zhang"
, return["Jason Zhang", "Bob Zhang"]
.
search"James"
, return["James Yu"]
.
Analysis
在client进行search之前就把所有的可能性都枚举出来。build up inverted index
通过一个Map来实现cache的效果,使得访问过的typeahead直接存储在Map中,因为Hash的速度是很快的,所以再次访问时直接从Hash中取出即可。
所谓的优化的核心都在于用空间换时间 Notice, when building up inverted index, you need to make sure no duplicated insert. For example, for different words, you may insert the same word for same substring multiple times
有点奇怪的问题,没有用到Trie,而是用了Inverted Index。
Solution
LintCode Official
注意:这个方法没有用Trie,不能算成标准的Typeahead实现方式,仅供一种思路参考。
Last updated