Replace Words

Problem Id: 648 Difficulty: Medium


Intuition

Solution


class Solution:
    def replaceWords(self, dict: List[str], sentence: str) -> str:
        if not sentence:
            return ''
        ans = ''
        dict = set(dict)
        for word in sentence.split(' '):
            tmp = ''
            for i in range(len(word)):
                tmp += word[i]
                if tmp in dict:
                    ans += tmp
                    break
            else:
                ans += tmp
            ans += ' '
        return ans[:-1]