|
1 | 1 | ### 642.Design-Search-Autocomplete-System
|
2 | 2 |
|
3 | | -如果不用trie来做的话,可以比较简单地用priority_queue来实现对所有候选语句的排序,选择最终未被弹出的三个字符串。 |
| 3 | +我们将所有的句子都构建入一棵字典树。对于每个节点(字母),我们都维护一个```句子-频次```的统计。也就是说,注入句子S时,我们将沿途经过的节点都标记上```freq[S]+=1```. |
4 | 4 |
|
5 | | -核心代码非常简单: |
6 | | -``` |
7 | | - struct cmp |
8 | | - { |
9 | | - bool operator()(pair<string,int>a, pair<string,int>b) |
10 | | - { |
11 | | - if (a.second==b.second) |
12 | | - return a.first<b.first; |
13 | | - else |
14 | | - return a.second>b.second; |
15 | | - } |
16 | | - }; |
17 | | - priority_queue<pair<string,int>,vector<pair<string,int>>,cmp>pq; |
18 | | - for (auto x:Map) |
19 | | - { |
20 | | - string a=x.first; |
21 | | - if (match(data,a)) |
22 | | - { |
23 | | - pq.push({a,Map[a]}); |
24 | | - if (pq.size()>3) pq.pop(); |
25 | | - } |
26 | | - } |
27 | | -``` |
| 5 | +当依次读入input时,我们维护从root往下走的指针,移动至该单词对应的节点,读取它的freq取出前三名即可。freq需要使用一个自动排序的数据结构。 |
28 | 6 |
|
| 7 | +记得当input遇到#时,要将之前input的完整句子,从root开始再次构建入这棵字典树。 |
29 | 8 |
|
30 | | -[Leetcode Link](https://leetcode.com/problems/design-search-autocomplete-system) |
| 9 | + |
| 10 | +[Leetcode Link](https://leetcode.com/problems/design-search-autocomplete-system) |
0 commit comments