forked from RajwardhanShinde/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathReplaceWords.cpp
56 lines (53 loc) · 1.39 KB
/
ReplaceWords.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
struct TrieNode {
bool end;
TrieNode *children[26];
TrieNode() {
end = false;
memset(children, NULL, sizeof(children));
}
};
class Trie {
public:
TrieNode *root;
Trie(vector<string>& dict) {
root = new TrieNode();
for(int i = 0; i < dict.size(); i++)
addWord(dict[i]);
}
void addWord(const string& s) {
TrieNode *dummy = root;
for(int i = 0; i < s.length(); i++) {
if(!dummy->children[s[i] - 'a'])
dummy->children[s[i] - 'a'] = new TrieNode;
dummy = dummy->children[s[i] - 'a'];
}
dummy->end = true;
}
};
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
Trie *trie = new Trie(dict);
TrieNode *root = trie->root;
stringstream ss(sentence);
string res, word;
while(ss >> word) {
res += search(root, word) + " ";
}
if(res != "")
res.pop_back();
return res;
}
string search(TrieNode *root, string& word){
TrieNode* t = root;
for(int i=0;i<word.length();i++){
if(t->end)
return word.substr(0,i);
if(t->children[word[i]-'a'])
t=t->children[word[i]-'a'];
else
return word;
}
return word;
}
};