-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathlcci17.17-multi-search-lcci_trie.cpp
77 lines (73 loc) · 1.85 KB
/
lcci17.17-multi-search-lcci_trie.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
73
74
75
76
77
#include<vector>
#include<algorithm>
#include<iostream>
#include<unordered_map>
using namespace std;
class Solution {
private:
struct Node {
int idx;
vector<Node*> children;
Node() : idx(-1), children(26, nullptr) {}
};
struct Trie {
Node* root;
Trie() : root(new Node()) {}
void insert(string& word, int idx)
{
Node* p = root;
for (char& c : word) {
c -= 'a';
if (p->children[c] == nullptr)
{
p->children[c] = new Node();
}
p = p->children[c];
}
p->idx = idx;
}
};
public:
vector<vector<int>> multiSearch(string big, vector<string>& smalls) {
unordered_map<string, vector<int>> cache;
const int n = big.size();
const int m = smalls.size();
vector<vector<int>> res(m);
Trie trie = Trie();
// 构造前缀树
for (int i = 0; i < m; i++)
{
trie.insert(smalls[i], i);
}
for (int i = 0; i < n; i++)
{
int j = i;
Node* node = trie.root;
while (j < n && node->children[big[j] - 'a'])
{
node = node->children[big[j] - 'a'];
if (node->idx != -1)
{
res[node->idx].push_back(i);
}
j++;
}
}
return res;
}
};
// Test
int main()
{
Solution sol;
string big = "mississippi";
vector<string> smalls = {"is", "ppi", "hi", "sis", "i", "ssippi"};
auto res = sol.multiSearch(big, smalls);
for (auto& row : res) // 遍历每一行
{
for (auto& elem : row) // 输出每一个元素
cout << elem << " ";
cout << "\n";
}
return 0;
}