Replace Words
Explanation & Solution
Description
In English, we have a concept called root, which can be followed by some other word to form another longer word — let us call that word a derivative. For example, when the root "help" is followed by "ful", we can form a derivative "helpful".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Output: "the cat was rat by the bat"
Explanation: "cattle" is replaced by "cat" (root), "rattled" is replaced by "rat", and "battery" is replaced by "bat".
Constraints
1 <= dictionary.length <= 10001 <= dictionary[i].length <= 100dictionary[i]consists of only lowercase letters1 <= sentence.length <= 10⁶sentenceconsists of only lowercase letters and spaces- The number of words in
sentenceis in the range[1, 1000] - The length of each word in
sentenceis in the range[1, 1000] - Every two consecutive words in
sentencewill be separated by exactly one space sentencedoes not have leading or trailing spaces
Approach
Trie pattern
1. Build a Trie from the Dictionary
- Create a trie root node
- For each root word in the dictionary, insert it character by character
- Mark the end of each root word with
isEnd = true
2. Split the Sentence into Words
- Use
split(' ')to break the sentence into individual words - Process each word independently
3. Search for the Shortest Root
- For each word, traverse the trie character by character
- If we reach a node with
isEnd = true, we found the shortest matching root - Replace the word with the substring from index 0 to the current position (inclusive)
- If no matching root is found (the path breaks), keep the original word
4. Reconstruct the Sentence
- Join all processed words back together with spaces
- Return the resulting string
Key Insight
- The trie naturally finds the shortest matching root because we traverse character by character and stop at the first
isEndwe encounter - Without a trie, we would need to check every root against every word, leading to inefficiency