Problem · String

Highlight Matching Phrases

Learn this problem
MediumHarvey logoHarveyFULLTIMEPHONE SCREEN

Problem statement

Given a sentence sentence and an array of literal phrases phrases, highlight every character that belongs to at least one occurrence of any phrase.

Matching is case-sensitive. Search for every occurrence, including overlapping occurrences. Merge overlapping or directly adjacent matched ranges, then wrap each merged range with <mark> and </mark>. Preserve every unmatched character exactly.

If no phrase occurs, return the original sentence.

Function

highlightMatches(sentence: String, phrases: String[]) → String

Examples

Example 1

sentence = "The quick brown fox jumps over the lazy dog."phrases = ["quick brown","brown fox jumps"]return = "The <mark>quick brown fox jumps</mark> over the lazy dog."

The two occurrences overlap on brown, so their ranges form one highlighted segment.

Example 2

sentence = "aaaa and aa"phrases = ["aa","aaa"]return = "<mark>aaaa</mark> and <mark>aa</mark>"

All overlapping occurrences in the first word merge into one range. The final occurrence is separated by unmatched text.

Example 3

sentence = "Case Sensitive"phrases = ["case","missing"]return = "Case Sensitive"

Lowercase case does not match uppercase Case, so the sentence is unchanged.

Constraints

  • 1 <= sentence.length <= 2 * 10^4
  • 1 <= phrases.length <= 200
  • 1 <= phrases[i].length <= 200
  • The sentence and phrases contain printable ASCII characters other than < and >.

More Harvey problems

drafts saved locally
public String highlightMatches(String sentence, String[] phrases) {
  // write your code here
}
sentence"The quick brown fox jumps over the lazy dog."
phrases["quick brown","brown fox jumps"]
expected"The <mark>quick brown fox jumps</mark> over the lazy dog."
checking account