Replace words
Warm-up · Write code · about 12 min
A dictionary holds root words. In sentence, replace every word that starts with a root by the shortest root it starts with. A word with no root stays as it is.
Return the new sentence. Words are separated by single spaces.
Example 1
Input:
[["cat","bat","rat"],"the cattle was rattled by the battery"]
Output:
the cat was rat by the bat
cattle starts with cat, rattled with rat and battery with bat.
Example 2
Input:
[["a","aa","aaa"],"aadsfasf absbs bbab aacc"]
Output:
a a bbab a
Both a and aa are roots. The shortest, a, wins.
Constraints
- 0 ≤ dictionary.length ≤ 1,000
- Each root has 1 to 100 lowercase letters
- sentence is lowercase words separated by single spaces, up to 2,000 characters; it may be empty
Learn the idea first: Trie applications: autocomplete, word search, XOR maximum, a visual lesson.
More Trie applications: autocomplete, word search, XOR maximum problems
- Autocomplete top-3 Standard
- Maximum XOR pair Standard
- Trace the XOR walk Standard
- Word search on a board Challenge