Skip to content

Commit caf33c7

Browse files
committed
Add C++ solution for "面试题 17.17. 多次搜索".
1 parent 44af0b8 commit caf33c7

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
#include<unordered_map>
5+
using namespace std;
6+
7+
class Solution {
8+
private:
9+
struct Node {
10+
int idx;
11+
vector<Node*> children;
12+
Node() : idx(-1), children(26, nullptr) {}
13+
};
14+
struct Trie {
15+
Node* root;
16+
Trie() : root(new Node()) {}
17+
void insert(string& word, int idx)
18+
{
19+
Node* p = root;
20+
for (char& c : word) {
21+
c -= 'a';
22+
if (p->children[c] == nullptr)
23+
{
24+
p->children[c] = new Node();
25+
}
26+
p = p->children[c];
27+
}
28+
p->idx = idx;
29+
}
30+
};
31+
public:
32+
vector<vector<int>> multiSearch(string big, vector<string>& smalls) {
33+
unordered_map<string, vector<int>> cache;
34+
const int n = big.length();
35+
const int m = smalls.size();
36+
vector<vector<int>> res(m);
37+
38+
Trie trie = Trie();
39+
// 构造前缀树
40+
for (int i = 0; i < m; i++)
41+
{
42+
trie.insert(smalls[i], i);
43+
}
44+
for (int i = 0; i < n; i++)
45+
{
46+
int j = i;
47+
Node* node = trie.root;
48+
while (j < n && node->children[big[j] - 'a'])
49+
{
50+
node = node->children[big[j] - 'a'];
51+
if (node->idx != -1)
52+
{
53+
res[node->idx].push_back(i);
54+
}
55+
j++;
56+
}
57+
}
58+
return res;
59+
}
60+
};
61+
62+
// Test
63+
int main()
64+
{
65+
Solution sol;
66+
string big = "mississippi";
67+
vector<string> smalls = {"is", "ppi", "hi", "sis", "i", "ssippi"};
68+
auto res = sol.multiSearch(big, smalls);
69+
for (auto& row : res) // 遍历每一行
70+
{
71+
for (auto& elem : row) // 输出每一个元素
72+
cout << elem << " ";
73+
cout << "\n";
74+
}
75+
76+
return 0;
77+
}

0 commit comments

Comments
 (0)