Show problems as
Classic problem #616MediumArrayHash TableStringTrieString MatchingAho–Corasick Algorithm

Add Bold Tag in String

Real-world version: Marking Up the Terms in a Line
Tracked in this browser only
Read Add Bold Tag in String on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A line of text line and a list of terms are given. Wherever a term turns up inside line, that stretch of the line has to be wrapped between the markers <hi> and </hi>.

Stretches may overlap or sit flush against each other. Use as few pairs of markers as possible, so any stretches that overlap or touch end up inside a single pair.

Return the marked-up line.

Examples

Example 1

Input
line = "hello world", terms = ["lo", "wor"]
Output
"hel<hi>lo</hi> <hi>wor</hi>ld"

One term sits at the fourth letter and the other starts the second word. The two stretches neither touch nor overlap, so each takes its own pair of markers.

Example 2

Input
line = "abcdef", terms = ["cd", "de"]
Output
"ab<hi>cde</hi>f"

The two stretches share the letter d, so they go inside a single pair of markers rather than two.

Example 3

Input
line = "abc", terms = []
Output
"abc"

With no terms to look for the line comes back untouched.

Constraints

  • 1 <= line.length <= 1000
  • 0 <= terms.length <= 100
  • 1 <= terms[i].length <= 1000
  • line and every term hold only English letters and digits
  • no two terms are the same

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def add_bold_tag(line: str, terms: list[str]) -> str:
Java
public String addBoldTag(String line, String[] terms)