题目:
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:
words
has length in range[0, 50]
.words[i]
has length in range[1, 10]
.S
has length in range[0, 500]
.- All characters in
words[i]
andS
are 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;
}
};