Given a string s and a list of strings dict, you need to add a closed pair of bold tag and to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, if two substrings wrapped by bold tags are consecutive, you need to combine them.
Example
Input:
s = "abcxyz123"
dict = ["abc","123"]
Output:
"<b>abc</b>xyz<b>123</b>"
Input:
s = "aaabbcc"
dict = ["aaa","aab","bc"]
Output:
"<b>aaabbc</b>c"
Notice
The given dict won't contain duplicates, and its length won't exceed 100.
All the strings in input have length in range [1, 1000].
分析
这道题可以使用set存放所有的word。使用一个另外的数组isTag记录s的每一位是否是需要加粗的。然后遍历s的子串,如果发现子串在dict中,则将isTag对应的位设置为true。
在遍历的时候我们可以使用另外一个set记录所有的word的长度,每次寻找子串是否在dict中时,我们先从最长的长度开始查找,如果找到了,接下来的就不用寻找了。
这道题当时想用TrieTree存放dict中的word,但是发现内存会爆掉。所以最后还是用set进行存放的。
Code
class Solution {
public:
/**
* @param s: a string
* @param dict: a list of strings
* @return: return a string
*/
string addBoldTag(string &s, vector<string> &dict) {
// write your code here
int dictLen = dict.size();
set<string> words;
set<int> lens;
int maxLen = 0;
for(int i = 0; i < dictLen; i ++)
{
words.insert(dict[i]);
lens.insert(dict[i].size());
}
vector<bool> isTag(s.size(), false);
for (int i = 0; i < s.size(); i ++)
{
set<int>::reverse_iterator it;
for (it = lens.rbegin(); it != lens.rend(); it ++)
{
if (words.find(s.substr(i, *it)) != words.end())
{
break;
}
}
if (it != lens.rend())
{
for (int j = i; j < i + *it; j ++)
isTag[j] = true;
}
}
string res;
bool add = false;
for (int i = 0; i < s.size(); i ++)
{
if (!add && isTag[i])
{
res += "<b>";
res.push_back(s[i]);
add = true;
}
else if (add && !isTag[i])
{
res += "</b>";
res.push_back(s[i]);
add = false;
}
else
{
res.push_back(s[i]);
}
}
if (add)
res += "</b>";
return res;
}
};
运行效率
Your submission beats 39.17% Submissions!
本文介绍了一种算法,用于在给定的字符串中查找并加粗包含在字典中的子字符串。通过使用set数据结构来高效查找和标记,确保了即使在子字符串重叠或连续时也能正确处理。

1342

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



