题目:
Given a set of keywords words and a string S,
make all appearances of all keywords in S bold. Any letters between <b> and </b>tags
become bold.
The returned string should use the least number of tags possible, and of course the tags should form a valid combination.
For example, given that words = ["ab", "bc"] and S
= "aabcd", we should return "a<b>abc</b>d". Note that returning "a<b>a<b>b</b>c</b>d" would
use more tags, so it is incorrect.
Note:
wordshas length in range[0, 50].words[i]has length in range[1, 10].Shas length in range[0, 500].- All characters in
words[i]andSare lowercase letters.
思路:
我们首先定义一个过滤器bolds,用来标记S中哪些字符都已经被加粗了,然后就在S中查找所有的words中的子串,如果找到了,就修改对应的bolds。最后根据过滤器bolds和原字符串S来构造返回结果。
代码:
class Solution {
public:
string boldWords(vector<string>& words, string S) {
vector<bool> bolds(S.length(), false);
for (string &word : words) { // try to find word in S
int start = 0;
while (start < S.length()) {
int index = S.find(word, start);
if (index == string::npos) {
break;
}
else {
for (int i = 0; i < word.length(); ++i) {
bolds[i + index] = true;
}
++start;
}
}
}
string ret;
for (int i = 0; i < S.length(); ++i) {
if ((i == 0 && bolds[0]) || (i > 0 && !bolds[i - 1] && bolds[i])) {
ret += "<b>";
}
ret.push_back(S[i]);
if ((i + 1 == S.length() && bolds[i]) || (i + 1 < S.length() && bolds[i] && !bolds[i + 1])) {
ret += "</b>";
}
}
return ret;
}
};
本文介绍了一种算法,用于在给定的字符串中将特定关键词加粗显示,并确保使用最少的HTML标签完成这一任务。该算法通过扫描字符串并标记关键词出现的位置来实现,最终返回带有适当加粗标签的字符串。
471

被折叠的 条评论
为什么被折叠?



