#648

Replace Words

pupil · 580 · lc medium +29 · verified · 68.7% accepted · 3,101 likes · top 76%

play →

Description

Given a dictionary of root words and a sentence, replace every word in the sentence that begins with a dictionary root with the shortest matching root. Words that have no root prefix are left unchanged. Return the modified sentence.

Example 1:

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

Example 2:

Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"

Code

1
2
3