Replace Words
https://leetcode.com/problems/replace-words/description/
In English, we have a concept called
root
, which can be followed by some other words to form another longer word - let's call this wordsuccessor
. For example, the rootan
, followed byother
, which can form another wordanother
.Now, given a dictionary consisting of many roots and a sentence. You need to replace all the
successor
in the sentence with theroot
forming it. If asuccessor
has manyroots
can form it, replace it with the root with the shortest length.You need to output the sentence after the replacement.
Thoughts
直观的想法,把每个单词的可能prefix找出来,看是否在dict里。
Code
Analysis
时间复制度O(n), n为总字符数。
Last updated
Was this helpful?