Leetcode 648. Replace Words

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Replace Words

2. Solution

解析:Version 1,将字典用map表示,遍历所有单词,遍历每个单词的前n个字符,判断是否在字典中,如果在,则替换单词。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
dictionary = {item: item for item in dictionary}
words = sentence.split(' ')
result = []
for word in words:
for i in range(1, len(word) + 1):
if word[:i] in dictionary:
word = word[:i]
break
result.append(word)
return ' '.join(result)

Reference

  1. https://leetcode.com/problems/replace-words/
如果有收获,可以请我喝杯咖啡!