forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7d629b3
commit f3ef226
Showing
1 changed file
with
5 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |