forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1408.cpp
43 lines (38 loc) · 905 Bytes
/
1408.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
const int M = 50010;
int son[M][27], nodes[M], idx;
void insert(string str) {
int p = 0;
for (char c : str) {
int& s = son[p][c - 'a'];
if (!s) s = ++idx;
son[s][26]++;
p = s;
}
}
bool get(string& str) {
int p = 0, s;
for (char c : str) {
s = son[p][c - 'a'];
if (!s) return false;
p = s;
}
return son[s][26] > 1;
}
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
memset(son, 0, sizeof son);
memset(nodes, 0, sizeof nodes);
idx = 0;
for (string& word : words) {
for (int i = 0; i < word.size(); i++) {
insert(word.substr(i));
}
}
vector<string> res;
for (string& word : words) {
if (get(word)) res.emplace_back(word);
}
return res;
}
};