648 Replace Words
648. Replace Words
1. Question
In English, we have a concept calledroot
, 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 thesuccessor
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.
Example 1:
Note:
The input will only have lower-case letters.
1 <= dict words number <= 1000
1 <= sentence words number <= 1000
1 <= root length <= 100
1 <= sentence words length <= 1000
2. Implementation
(1) Trie
思路: 很典型的查询prefix的应用,所以用trie很适合,只要在trieNode的基础上加入字典里的string所对应的index即可
3. Time & Space Complexity
Trie: 时间复杂度O(n * m), n是dict里面string的个数,m是string的平均长度。 空间复杂度O(nm)
Last updated