文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
解析:Version 1,将字典用map
表示,遍历所有单词,遍历每个单词的前n
个字符,判断是否在字典中,如果在,则替换单词。
- Version 1
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)