-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0648.ReplaceWords.cpp
More file actions
79 lines (64 loc) · 1.87 KB
/
0648.ReplaceWords.cpp
File metadata and controls
79 lines (64 loc) · 1.87 KB
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
76
77
78
79
class Solution {
public:
struct StringNode {
string m_string;
StringNode* m_children[26];
StringNode() : m_string("") {
// Set children to nullptr.
for (int i = 0; i < sizeof(m_children) / sizeof(*m_children); i++)
m_children[i] = nullptr;
}
void addString(const char* string, const char* baseString) {
// Check if string finished.
if (string[0] == '\0') {
// Valid end point.
m_string = baseString;
return;
}
// Get child.
StringNode*& child = m_children[string[0] - 'a'];
if (child == nullptr)
// Create child.
child = new StringNode();
// Add remainder of string.
child->addString(string + 1, baseString);
}
const char* validString(const char* string) {
if (string[0] == '\0' || m_string[0] != '\0') return m_string.c_str();
// Get child.
StringNode*& child = m_children[string[0] - 'a'];
// Child if child exists.
if (child == nullptr) return m_string.c_str();
// Recurse.
return child->validString(string + 1);
}
};
string replaceWords(vector<string>& dictionary, string sentence) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Create root.
StringNode root;
for (const string& word : dictionary)
root.addString(word.c_str(), word.c_str());
// Create resultant sentence.
const int n = sentence.size();
string activeWord, resultantSentence = "";
for (int i = 0; i < n; i++) {
// Reset states.
activeWord = "";
// Find word in dictionary.
for (; i < n && sentence[i] != ' '; i++) {
// Update active word.
activeWord += sentence[i];
}
// Add space.
if (resultantSentence.size() > 0) resultantSentence += ' ';
// Get valid word.
const char* validWord = root.validString(activeWord.c_str());
resultantSentence += (validWord[0] != '\0') ? validWord : activeWord;
}
return resultantSentence;
}
};