-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
shortest-uncommon-substring-in-an-array.cpp
68 lines (62 loc) · 1.78 KB
/
shortest-uncommon-substring-in-an-array.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
// Time: O(n * l^2)
// Space: O(t)
// trie
class Solution {
private:
class Trie {
public:
Trie() {
new_node();
}
void add(const string& s, int d) {
for (int i = 0; i < size(s); ++i) {
int curr = 0;
for (int j = i; j < size(s); ++j) {
const int x = s[j] - 'a';
if (nodes_[curr][x] == -1) {
nodes_[curr][x] = new_node();
}
curr = nodes_[curr][x];
cnts_[curr] += d;
}
}
}
string query(const string& s) {
pair<int, string> result = {numeric_limits<int>::max(), ""};
for (int i = 0; i < size(s); ++i) {
int curr = 0;
for (int j = i; j < size(s); ++j) {
const int x = s[j] - 'a';
curr = nodes_[curr][x];
if (cnts_[curr] == 0) {
result = min(result, {j - i + 1, s.substr(i, j - i + 1)});
break;
}
}
}
return result.second;
}
private:
int new_node() {
nodes_.emplace_back(26, -1);
cnts_.emplace_back(0);
return size(nodes_) - 1;
}
vector<vector<int>> nodes_;
vector<int> cnts_;
};
public:
vector<string> shortestSubstrings(vector<string>& arr) {
Trie trie;
for (const auto& x : arr) {
trie.add(x, +1);
}
vector<string> result;
for (const auto& x: arr) {
trie.add(x, -1);
result.emplace_back(trie.query(x));
trie.add(x, +1);
}
return result;
}
};