forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bold-words-in-string.cpp
94 lines (85 loc) · 2.6 KB
/
bold-words-in-string.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Time: O(n * l), n is the length of S, l is the average length of words
// Space: O(t) , t is the size of trie
class Solution {
public:
string boldWords(vector<string>& words, string S) {
TrieNode trie;
for (const auto& word : words) {
trie.Insert(word);
}
vector<bool> lookup(S.length());
for (int i = 0; i < S.length(); ++i) {
auto curr = ≜
int k = i - 1;
for (int j = i; j < S.length(); ++j) {
if (!curr->leaves[S[j] - 'a']) {
break;
}
curr = curr->leaves[S[j] - 'a'];
if (curr->isString) {
k = j;
}
}
fill(lookup.begin() + i, lookup.begin() + k + 1, true);
}
string result;
for (int i = 0; i < S.length(); ++i) {
if (lookup[i] && (i == 0 || !lookup[i - 1])) {
result += "<b>";
}
result.push_back(S[i]);
if (lookup[i] && (i == (S.length() - 1) || !lookup[i + 1])) {
result += "</b>";
}
}
return result;
}
private:
struct TrieNode {
bool isString;
vector<TrieNode *> leaves;
TrieNode() : isString{false}, leaves(26) {}
void Insert(const string& s) {
auto* p = this;
for (const auto& c : s) {
if (!p->leaves[c - 'a']) {
p->leaves[c - 'a'] = new TrieNode;
}
p = p->leaves[c - 'a'];
}
p->isString = true;
}
~TrieNode() {
for (auto& node : leaves) {
if (node) {
delete node;
}
}
}
};
};
// Time: O(n * d * l), l is the average length of words
// Space: O(n)
class Solution2 {
public:
string boldWords(vector<string>& words, string S) {
vector<bool> lookup(S.length());
for (const auto& d: words) {
auto pos = -1;
while ((pos = S.find(d, pos + 1)) != string::npos) {
fill(lookup.begin() + pos, lookup.begin() + pos + d.length(), true);
}
}
string result;
for (int i = 0; i < S.length(); ++i) {
if (lookup[i] && (i == 0 || !lookup[i - 1])) {
result += "<b>";
}
result.push_back(S[i]);
if (lookup[i] && (i == (S.length() - 1) || !lookup[i + 1])) {
result += "</b>";
}
}
return result;
}
};