返回题库

设计搜索自动补全系统

Design Search Autocomplete System

专题
Algorithmic Programming / 算法编程
难度
L4
来源
Citadel

题目详情

问题:设计搜索自动补全系统

考察:字符串、树、贪心、数组

来源:Citadel

链接:https://www.jointaro.com/interviews/questions/design-search-autocomplete-system/

Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). For each character they type except '#', you need to return the top 3 historical hot sentences that match the prefix of the part sentence before the current character. For each input sentence, when the character is '#', it means the sentence ends, and you need to store the complete sentence into the historical data.

Implement the AutocompleteSystem class:

  • AutocompleteSystem(String[] sentences, int[] times) Initializes the object with a list of historical sentences and their corresponding number of times each sentence was typed.
  • List<String> input(char c)
    • If c == '#', it means the sentence ends, and you need to store the complete sentence into the historical data.
    • Otherwise, you need to return the top 3 historical hot sentences that match the prefix of the part sentence before the current character.

Example 1:

Input
["AutocompleteSystem", "input", "input", "input", "input"]
[[["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]], ["i"], [" "], ["a"], ["#"]]
Output
[null, ["i love you", "island", "i love leetcode"], [], [], []]

Explanation
AutocompleteSystem obj = new AutocompleteSystem(["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]);
obj.input("i"); // return ["i love you", "island", "i love leetcode"], because "i love you" has highest times.
obj.input(" "); // return []. There's no match.
obj.input("a"); // return []. There's no match.
obj.input("#"); // return []. The sentence "i a" was typed. Store the string to the record.

Example 2:

Input
["AutocompleteSystem", "input", "input", "input", "input"]
[[["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]], ["i"], [" "], ["a"], ["#"]]
Output
[null, ["i love you", "island", "i love leetcode"], [], [], []]

Explanation
AutocompleteSystem obj = new AutocompleteSystem(["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]);
obj.input("i"); // return ["i love you", "island", "i love leetcode"], because "i love you" has highest times.
obj.input(" "); // return []. There's no match.
obj.input("a"); // return []. There's no match.
obj.input("#"); // return []. The sentence "i a" was typed. Store the string to the record.

Constraints:

  • 1 <= sentences.length <= 100
  • 1 <= sentences[i].length <= 100
  • 1 <= times.length <= 100
  • times[i] >= 1
  • c is a lowercase English letter, space ' ' or special character '#'
  • Each input will be ended with the character '#'.

解析

思路:使用 Trie 存储历史句子,每个节点维护经过该前缀的候选句子及热度。输入字符时沿 Trie 下移并返回热度高、字典序小的前三项;输入 # 时把当前句子写回 Trie。

复杂度:输入查询与前缀长度和候选维护方式相关;若每节点保留前三项,单字符查询可接近 O(1)。