您的位置:首页 > 编程语言 > Python开发

【LeetCode】648. Replace Words 解题报告(Python)

2018-02-27 18:08 876 查看

【LeetCode】648. Replace Words 解题报告(Python)

标签(空格分隔): LeetCode

题目地址: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 word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:
Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"


Note:

1. The input will only have lower-case letters.

1. 1 <= dict words number <= 1000

1. 1 <= sentence words number <= 1000

1. 1 <= root length <= 100

1. 1 <= sentence words length <= 1000

题目大意

把句子中的每个单词用给的字典进行替换,替换时优先替换成最短的词。替换就是找出最短的头部匹配;如果字典中不存在,就保留原来的词。

解题方法

看了下给出的Note,发现并没有特别长,普通的方法应该就能搞定,不会超时。

下面的方法叫做Prefix Hash,对于python而言就是用了set的意思。

class Solution(object):
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
rootset = set(dict)
def replace(word):
for i in xrange(len(word)):
if word[:i] in rootset:
return word[:i]
return word
return ' '.join(map(replace, sentence.split()))


方法二:

字典树Trie,未完待续。。

Date

2018 年 2 月 27 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: