-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign-search-autocomplete-system.cpp
72 lines (58 loc) · 1.41 KB
/
design-search-autocomplete-system.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Copyright (c) 2019 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
// https://leetcode.com/problems/design-search-autocomplete-system/
class AutocompleteSystem {
public:
unordered_set<string> sen;
unordered_map<string, int> tim;
string q;
AutocompleteSystem(vector<string> &sentences, vector<int> ×) {
for (size_t i = 0; i < sentences.size(); i++) {
sen.insert(sentences[i]);
tim[sentences[i]] = times[i];
}
}
vector<string> input(char c) {
vector<string> res;
if ('#' == c) {
sen.insert(q);
tim[q]++;
q = "";
return res;
}
q.push_back(c);
for (auto &s : sen) {
if (s.substr(0, q.size()) == q) {
res.push_back(s);
}
}
auto cmp = [&](const string &s1, const string &s2) -> bool {
if (tim[s2] < tim[s1]) {
return true;
}
if (tim[s2] == tim[s1] && s2 > s1) {
return true;
}
return false;
};
sort(res.begin(), res.end(), cmp);
if (res.size() > 3) {
res.erase(res.begin() + 3, res.end());
}
return res;
}
};
/**
* Your AutocompleteSystem object will be instantiated and called as such:
* AutocompleteSystem* obj = new AutocompleteSystem(sentences, times);
* vector<string> param_1 = obj->input(c);
*/