-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
45 lines (42 loc) · 1.07 KB
/
Solution.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
class Trie {
public:
vector<Trie*> children;
string v;
Trie()
: children(26)
, v("") {}
void insert(string word) {
Trie* node = this;
for (char c : word) {
c -= 'a';
if (!node->children[c]) node->children[c] = new Trie();
node = node->children[c];
}
node->v = word;
}
string search(string word) {
Trie* node = this;
for (char c : word) {
c -= 'a';
if (!node->children[c]) break;
node = node->children[c];
if (node->v != "") return node->v;
}
return word;
}
};
class Solution {
public:
string replaceWords(vector<string>& dictionary, string sentence) {
Trie* trie = new Trie();
for (auto& v : dictionary) trie->insert(v);
string ans = "";
istringstream is(sentence);
vector<string> ss;
string s;
while (is >> s) ss.push_back(s);
for (auto word : ss) ans += trie->search(word) + " ";
ans.pop_back();
return ans;
}
};