930. Replace Words Using Trie (Sentence Shortening)

MediumTreesTrieStringHash

Given a list of root words and a sentence, replace every word in the sentence with the shortest root that is a prefix of it (if any such root exists); otherwise keep the word unchanged. Return the resulting sentence. The input is JSON {roots, sentence}.

Input: JSON {roots, sentence}.

Output: Quoted string — the transformed sentence.

Examples

Example 1
Input: {"roots":["cat","bat","rat"],"sentence":"the cattle was rattled by the battery"}
Output: "the cat was rat by the bat"
Explanation: Each word shortened to its root.
Example 2
Input: {"roots":["a","b","c"],"sentence":"aadsfasf absbs bbab cadsfafs"}
Output: "a a b c"
Explanation: Single-letter roots.
Example 3
Input: {"roots":["se"],"sentence":"success is here"}
Output: "se is here"
Explanation: Only 'success' has a root.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →