-
Notifications
You must be signed in to change notification settings - Fork 3
/
648.cpp
61 lines (61 loc) · 1.5 KB
/
648.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
class TrieNode {
public:
vector<TrieNode*> children;
bool isEnd = false;
TrieNode() {
children.resize(26, nullptr);
}
};
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
void insert(string &s) {
TrieNode* current = root;
for (auto &c : s) {
if (!current->children[c - 'a']) {
current->children[c - 'a'] = new TrieNode();
}
current = current->children[c - 'a'];
}
current->isEnd = true;
}
int search(string& s) {
TrieNode* current = root;
int res = 0;
for (auto &c : s) {
if (!current->children[c - 'a']) return -1;
current = current->children[c - 'a'];
res += 1;
if (current->isEnd) return res;
}
return res;
}
};
class Solution {
public:
string replaceWords(vector<string>& dictionary, string sentence) {
Trie* trie = new Trie();
for (auto& word : dictionary) {
trie->insert(word);
}
stringstream ss(sentence);
string token;
string res = "";
while (getline(ss, token, ' ')) {
int index = trie->search(token);
if (index != -1) {
string substring = token.substr(0, index);
res += substring;
}
else {
res += token;
}
res += " ";
}
res.pop_back();
return res;
}
};