【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 calledroot, 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 日相关文章推荐
- 【LeetCode】529. Minesweeper 解题报告(Python)
- 【LeetCode】Two Sum 解题报告(java & python)
- 【LeetCode】521. Longest Uncommon Subsequence I 解题报告(Python)
- 【LeetCode】Linked List Cycle 解题报告(Java & Python)
- 【LeetCode】655. Print Binary Tree 解题报告(Python)
- 【LeetCode】565. Array Nesting 解题报告(Python)
- LeetCode 227. Basic Calculator II 解题报告【python】
- 【LeetCode】208. Implement Trie (Prefix Tree) 解题报告(Python)
- 【LeetCode】667. Beautiful Arrangement II 解题报告(Python)
- 【LeetCode】495. Teemo Attacking 解题报告(Python)
- 【LeetCode】240. Search a 2D Matrix II 解题报告(Python)
- 【LeetCode】553. Optimal Division 解题报告(Python)
- 【LeetCode】Binary Tree Paths 解题报告(java & python)
- 【LeetCode】Reverse Linked List 解题报告(Python & java)
- 【LeetCode】677. Map Sum Pairs 解题报告(Python)
- 【LeetCode】Group Anagrams 解题报告(Python & Java)
- Leetcode 529 python 解题报告
- 【LeetCode】791. Custom Sort String 解题报告(Python)
- 【LeetCode】676. Implement Magic Dictionary 解题报告(Python)
- Leetcode 451 python 解题报告