forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 15
/
replace-words.cpp
50 lines (46 loc) · 1.25 KB
/
replace-words.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
// Time: O(n)
// Space: O(t), t is the number of nodes in trie
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
TrieNode trie;
string result;
for (const auto& s : dict) {
trie.Insert(s);
}
auto curr = ≜
for (const auto& c : sentence) {
if (c == ' ' || !curr || !curr->isString) {
result += c;
}
if (c == ' ') {
curr = ≜
} else if (curr && !curr->isString) {
curr = curr->leaves[c];
}
}
return result;
}
private:
struct TrieNode {
bool isString = false;
unordered_map<char, TrieNode *> leaves;
void Insert(const string& s) {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
p->leaves[c] = new TrieNode;
}
p = p->leaves[c];
}
p->isString = true;
}
~TrieNode() {
for (auto& kv : leaves) {
if (kv.second) {
delete kv.second;
}
}
}
};
};