forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Replace_Words.cpp
75 lines (70 loc) · 2.13 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Solution {
class trieNode {
public:
int keyId;
unordered_map<char, trieNode*> children;
trieNode(): keyId(-1), children(unordered_map<char, trieNode*>()) {
}
};
class trie {
public:
trieNode* root;
trie(): root(new trieNode()) {
}
void insert(string& key, int keyId) {
trieNode* pCrawl = root;
for(int i = 0; i < key.length(); i++) {
if(!pCrawl->children[key[i]]) {
pCrawl->children[key[i]] = new trieNode();
}
pCrawl = pCrawl->children[key[i]];
}
pCrawl->keyId = keyId;
}
int search(string& key) {
trieNode* pCrawl = root;
for(int i = 0; i < key.length(); i++) {
if(!pCrawl->children[key[i]]) {
return -1;
}
pCrawl = pCrawl->children[key[i]];
if(pCrawl->keyId >= 0) {
return pCrawl->keyId;
}
}
return -1;
}
};
public:
string replaceWords(vector<string>& dict, string sentence) {
string resultSentence;
unordered_map<int, string> keyIdMap;
trie* Trie = new trie();
for(int i = 0; i < dict.size(); i++) {
Trie->insert(dict[i], i);
keyIdMap[i] = dict[i];
}
int i = 0;
while(i < sentence.length()) {
int spaces = 0;
while(i < sentence.length() and sentence[i] == ' ') {
i++;
++spaces;
}
int start = i;
while(i < sentence.length() and isalnum(sentence[i])) {
i++;
}
string word = sentence.substr(start, i - start);
resultSentence += string(spaces, ' ');
int keyId = Trie->search(word);
if(keyId >= 0) {
string root = keyIdMap[keyId];
resultSentence += root;
} else {
resultSentence += word;
}
}
return resultSentence;
}
};