Add Bold Tag in String - Problem
You are given a string s and an array of strings words. You should add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in words.
Rules for bold tagging:
- If two such substrings overlap, you should wrap them together with only one pair of bold tags
- If two substrings wrapped by bold tags are consecutive, you should combine them
Return s after adding the bold tags.
Input & Output
Example 1 — Basic Case
$
Input:
s = "abcxyz123", words = ["abc", "123"]
›
Output:
"<b>abc</b>xyz<b>123</b>"
💡 Note:
"abc" appears at start (positions 0-2) and "123" appears at end (positions 6-8). Both are wrapped with bold tags separately since they don't overlap.
Example 2 — Overlapping Words
$
Input:
s = "aaabbcc", words = ["aaa", "aab", "bc"]
›
Output:
"<b>aaabbc</b>c"
💡 Note:
"aaa" matches at 0-2, "aab" matches at 1-3, "bc" matches at 4-5. Since positions 0-5 are all marked bold and consecutive, they merge into one bold tag.
Example 3 — No Matches
$
Input:
s = "hello", words = ["world", "test"]
›
Output:
"hello"
💡 Note:
None of the words appear in the string, so no bold tags are added.
Constraints
- 1 ≤ s.length ≤ 1000
- 0 ≤ words.length ≤ 100
- 1 ≤ words[i].length ≤ 100
- s and words[i] consist of English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original string and array of words to highlight
2
Find Matches
Locate all occurrences of words in the string
3
Add Tags
Wrap matching substrings with bold tags, merging overlaps
Key Takeaway
🎯 Key Insight: Mark character positions first, then merge consecutive bold regions to handle overlaps automatically
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code