25 · Tries

#648 Replace Words

Mediumsolve on LeetCode ↗

frequently reported atByteDance / TikTokMicrosoftGoogle

the problem

In plain words

Given a dictionary of roots and a sentence, replace every word in the sentence by the shortest root that is a prefix of it. Words with no root stay unchanged.

in dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"

out "the cat was rat by the bat"

in dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"

out "a a b c"

  • 1 ≤ dictionary.length ≤ 1000
  • 1 ≤ dictionary[i].length ≤ 100
  • 1 ≤ sentence.length ≤ 10⁶
  • Words separated by single spaces

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #208
    2. #720
    3. #14
      Longest Common Prefix
      Easyin Arrays & Strings