Skip to content

Commit

Permalink
Update Readme.md
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Jun 19, 2022
1 parent 7d629b3 commit f3ef226
Showing 1 changed file with 5 additions and 25 deletions.
30 changes: 5 additions & 25 deletions Design/642.Design-Search-Autocomplete-System/Readme.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,10 @@
### 642.Design-Search-Autocomplete-System

如果不用trie来做的话,可以比较简单地用priority_queue来实现对所有候选语句的排序,选择最终未被弹出的三个字符串。
我们将所有的句子都构建入一棵字典树。对于每个节点(字母),我们都维护一个```句子-频次```的统计。也就是说,注入句子S时,我们将沿途经过的节点都标记上```freq[S]+=1```.

核心代码非常简单:
```
struct cmp
{
bool operator()(pair<string,int>a, pair<string,int>b)
{
if (a.second==b.second)
return a.first<b.first;
else
return a.second>b.second;
}
};
priority_queue<pair<string,int>,vector<pair<string,int>>,cmp>pq;
for (auto x:Map)
{
string a=x.first;
if (match(data,a))
{
pq.push({a,Map[a]});
if (pq.size()>3) pq.pop();
}
}
```
当依次读入input时,我们维护从root往下走的指针,移动至该单词对应的节点,读取它的freq取出前三名即可。freq需要使用一个自动排序的数据结构。

记得当input遇到#时,要将之前input的完整句子,从root开始再次构建入这棵字典树。

[Leetcode Link](https://leetcode.com/problems/design-search-autocomplete-system)

[Leetcode Link](https://leetcode.com/problems/design-search-autocomplete-system)

0 comments on commit f3ef226

Please sign in to comment.