Replace Words
Given a dictionary of root words and a sentence, replace every word in the sentence with the shortest root in the dictionary that is a prefix of it. If no root is a prefix, keep the word unchanged. Return the resulting sentence.
Open official problem prompt ↗Rewrite each word in a sentence to the shortest dictionary root that begins it, leaving unmatched words alone.
Like autocorrect shrinking 'cattle' to its known stem 'cat' the instant it recognizes a complete root, not waiting to read the rest of the word.
- Input
- dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
- Output
- "the cat was rat by the bat"
- Why
- "cattle" -> "cat", "rattled" -> "rat", "battery" -> "bat"; words with no root prefix stay the same.
1 <= dictionary.length <= 10001 <= dictionary[i].length <= 100dictionary[i] consists of only lowercase letters1 <= sentence.length <= 10^6words in sentence are separated by single spaces1 <= word length <= 1000