Mid/Senior

Add Bold Tag in String

Given a string s and an array of strings words, add a closed pair of bold tags <b> and </b> to wrap every substring in s that matches any word in words.

When adding tags, follow these rules:

  • If two matching substrings overlap, wrap them together with a single pair of bold tags.
  • If two matching substrings are adjacent, combine them into one bold section.
  • Only the minimal necessary bold tags should be inserted.

Return the resulting string after inserting the bold tags.

Example 1
Inputs = "abcxyz123", words = ["abc","123"]
Output"<b>abc</b>xyz<b>123</b>"
The substrings abc and 123 match words, so each is wrapped in bold tags.
Example 2
Inputs = "aaabbcc", words = ["aaa","aab","bc"]
Output"<b>aaabbc</b>c"
The matches aaa, aab, and bc overlap or touch, so the combined substring aaabbc is wrapped once.

Constraints

  • 1 <= s.length <= 1000
  • 0 <= words.length <= 100
  • 1 <= words[i].length <= 1000
  • s and words[i] consist of lowercase English letters and digits

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate