LeetCode 454. 4Sum II: CPP Solution

Problem Statement

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.

``````Function Signature (C++):

Inputs:
s = "abcxyz123"
dict = ["abc","123"]

Outputs:
"<b>abc</b>xyz<b>123</b>"

Inputs:
s = "aaabbcc"
dict = ["aaa","aab","bc"]

Outputs:
"<b>aaabbc</b>c"
``````

TL;DR Code Solution

``````string addBoldTag(string s, vector<string>& dict) {

vector<bool> isBold(s.length());
for (int i = 0; i < dict.size(); i++) {
int searchIndex = s.find(dict[i], 0);
while (s.find(dict[i], searchIndex) != std::string::npos) {
for (int j = searchIndex; j < searchIndex + dict[i].length(); j++) {
isBold[j] = true;
}
searchIndex = s.find(dict[i], searchIndex + 1);
}

}

int runner = 0;
string result;
while (runner < s.length()) {
if (!isBold[runner]) {
result += s[runner];
runner++;
}
else {
result += "<b>";
while (runner < s.length() && isBold[runner]) {
result += s[runner];
runner++;
}
result += "</b>";
}
}

return result;
}
``````