embolding cpp

This commit is contained in:
NaiJi ✨ 2024-04-10 23:38:10 +04:00
parent 62db3677e3
commit 80c7cab5b6
1 changed files with 73 additions and 0 deletions

73
cpp/string_embolding.cpp Normal file
View File

@ -0,0 +1,73 @@
#include <iostream>
#include <string>
#include <vector>
std::vector<bool> buildMask(const std::string& main_string, const std::vector<std::string>& substrings)
{
std::vector<bool> bold_mask(main_string.size(), false);
for (const auto& substring : substrings)
{
const auto substring_index = main_string.find(substring);
if (substring_index != main_string.npos)
{
for (size_t mask_i = substring_index; mask_i < substring_index + substring.size(); ++mask_i)
{
bold_mask[mask_i] = true;
}
}
}
return bold_mask;
}
std::string emboldenString(const std::string& main_string, const std::vector<std::string>& substrings)
{
std::vector<bool> bold_mask = buildMask(main_string, substrings);
std::string embolded_string;
bool is_bold_now = false;
for (size_t mask_i = 0; mask_i < bold_mask.size(); ++mask_i)
{
if (!is_bold_now)
{
if (bold_mask[mask_i])
{
embolded_string += "<b>";
embolded_string += main_string[mask_i];
is_bold_now = true;
}
else
{
embolded_string += main_string[mask_i];
}
}
else
{
if (bold_mask[mask_i])
{
embolded_string += main_string[mask_i];
}
else
{
embolded_string += "</b>";
embolded_string += main_string[mask_i];
is_bold_now = false;
}
}
}
if (is_bold_now)
{
embolded_string += "</b>";
}
return embolded_string;
}
int main()
{
std::string main_string = "I despise leetcode kind of problems.";
std::vector<std::string> substrings = {"despise", "pise", "I", "s."};
std::cout << emboldenString(main_string, substrings) << '\n';
}