Problem solution · C++

Add Bold Tag in String

Add Bold Tag in String: a C++ solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
34 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Add Bold Tag in String, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 34 lines of C++ from the credited upstream file 616.cpp.
  • The implementation visibly relies on sequence storage.
  • 4 loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeAdd Bold Tag in String · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  string addBoldTag(string s, vector<string>& words) {    const int n = s.length();    string ans;    // bold[i] := true if s[i] should be bolded    vector<bool> bold(n);     int boldEnd = -1;  // s[i:boldEnd] should be bolded    for (int i = 0; i < n; ++i) {      for (const string& word : words)        if (s.substr(i).find(word) == 0)  // StartsWith          boldEnd = max(boldEnd, i + static_cast<int>(word.length()));      bold[i] = boldEnd > i;    }     // Construct the string with the bold tags.    int i = 0;    while (i < n)      if (bold[i]) {        int j = i;        while (j < n && bold[j])          ++j;        // `s[i..j)` should be bolded.        ans += "<b>" + s.substr(i, j - i) + "</b>";        i = j;      } else {        ans += s[i++];      }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗