Replace Words
A root is a short string that longer words can be built from by adding letters at the end: "re" is a root of "reread" and of "return".
You are given a list of roots, dictionary, and a sentence made of words separated by single spaces. Replace every word in the sentence that starts with some root by that root. If several roots match the same word, use the shortest one. Words that start with no root stay as they are.
Return the sentence after all replacements, with the words still separated by single spaces.
Constraints
1 <= dictionary.length <= 10001 <= dictionary[i].length <= 1001 <= sentence.length <= 10^6- The dictionary and the sentence use lowercase English letters; the sentence also has single spaces between words and none at either end.
Examples
Example 1
Input: dictionary = ["pre","un","re"], sentence = "unhappy readers prefer reruns" Output: "un re pre re"
"unhappy" starts with "un", "readers" and "reruns" with "re", and "prefer" with "pre".
Example 2
Input: dictionary = ["a","aa","aaa"], sentence = "aaaa aa a b" Output: "a a a b"
Every word made of a's starts with all three roots; the shortest, "a", wins. "b" has no root and stays.
Example 3
Input: dictionary = ["xyz"], sentence = "hello world" Output: "hello world"
No word starts with "xyz", so the sentence is unchanged.
JavaScript you'll use: Strings and characters Map and Set
/**
* @param {string[]} dictionary
* @param {string} sentence
* @return {string}
*/
function replaceWords(dictionary, sentence) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.