代码拉取完成,页面将自动刷新
// 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;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。