Leetcode 648. Replace Words

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 648. Replace Words相关的知识,希望对你有一定的参考价值。

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

1. Description

Replace Words

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)

Reference

  1. https://leetcode.com/problems/replace-words/

以上是关于Leetcode 648. Replace Words的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 648. Replace Words (单词替换)

Leetcode 648. Replace Words

648.replace words

648. Replace Words

648. Replace Words 替换单词

648. Replace Words (Medium)