forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
46 lines (43 loc) · 1.08 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
46
class Trie {
public:
string root;
vector<Trie*> children;
Trie() {
root = "";
children.resize(26);
}
};
class Solution {
public:
string replaceWords(vector<string>& dictionary, string sentence) {
Trie* trie = new Trie();
for (auto root : dictionary)
{
Trie* cur = trie;
for (char c : root)
{
if (!cur->children[c - 'a']) cur->children[c - 'a'] = new Trie();
cur = cur->children[c - 'a'];
}
cur->root = root;
}
string ans = "";
istringstream is(sentence);
vector<string> ss;
string s;
while (is >> s) ss.push_back(s);
for (auto word : ss)
{
Trie* cur = trie;
for (char c : word)
{
if (!cur->children[c - 'a'] || cur->root != "") break;
cur = cur->children[c - 'a'];
}
ans += cur->root == "" ? word : cur->root;
ans += " ";
}
ans.pop_back();
return ans;
}
};