-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathapply-substitutions.cpp
119 lines (113 loc) · 3.6 KB
/
apply-substitutions.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// Time: O(r * 2^r)
// Space: O(r * 2^r)
// topological sort
class Solution {
public:
string applySubstitutions(vector<vector<string>>& replacements, string text) {
unordered_map<string, string> lookup;
const auto& find_adj = [&](const auto& s) {
unordered_set<string> result;
for (int i = 0; i < size(s); ++i) {
if (s[i] != '%') {
continue;
}
int j = i + 1;
for (; j < size(s); ++j) {
if (s[j] == '%') {
break;
}
}
result.emplace(s.substr(i + 1, j - (i + 1)));
i = j;
}
return result;
};
const auto& replace = [&](const auto& s) {
string result;
for (int i = 0; i < size(s); ++i) {
if (s[i] != '%') {
result.push_back(s[i]);
continue;
}
int j = i + 1;
for (; j < size(s); ++j) {
if (s[j] == '%') {
break;
}
}
result += lookup[s.substr(i + 1, j - (i + 1))];
i = j;
}
return result;
};
const auto& topological_sort = [&]() {
unordered_map<string, unordered_set<string>> adj;
unordered_map<string, int> in_degree;
for (const auto& x : replacements) {
for (const auto& v : find_adj(x[1])) {
adj[v].emplace(x[0]);
++in_degree[x[0]];
}
}
vector<string> q;
for (const auto& x : replacements) {
if (!in_degree.count(x[0])) {
q.emplace_back(x[0]);
}
}
while (!empty(q)) {
vector<string> new_q;
for (const auto& u : q) {
lookup[u] = replace(lookup[u]);
for (const auto& v : adj[u]) {
--in_degree[v];
if (in_degree[v]) {
continue;
}
new_q.emplace_back(v);
}
}
q = move(new_q);
}
};
for (const auto& x : replacements) {
lookup[x[0]] = x[1];
}
topological_sort();
return replace(text);
}
};
// Time: O(r * 2^r)
// Space: O(r * 2^r)
// memoization
class Solution2 {
public:
string applySubstitutions(vector<vector<string>>& replacements, string text) {
unordered_map<string, string> lookup, memo;
const function<string (const string&)> replace = [&](const auto& s) {
if (!memo.count(s)) {
string result;
for (int i = 0; i < size(s); ++i) {
if (s[i] != '%') {
result.push_back(s[i]);
continue;
}
int j = i + 1;
for (; j < size(s); ++j) {
if (s[j] == '%') {
break;
}
}
result += replace(lookup[s.substr(i + 1, j - (i + 1))]);
i = j;
}
memo[s] = result;
}
return memo[s];
};
for (const auto& x : replacements) {
lookup[x[0]] = x[1];
}
return replace(text);
}
};