648. 单词替换

exiaohu 于 2022-07-07 发布

题目链接:648. 单词替换

两个优化:

from typing import List


class tire(object):
    def __init__(self, dictionary: List[str]):
        self.roots = set()
        self.max_len = 0

        for word in sorted(dictionary, key=len):
            for i in range(1, len(word) + 1):
                if word[:i] in self.roots:
                    break
            else:
                self.roots.add(word)
                self.max_len = max(len(word), self.max_len)

    def root(self, word: str) -> str:
        for i in range(1, self.max_len + 1):
            if word[:i] in self.roots:
                return word[:i]
        return word


class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        t = tire(dictionary)
        return ' '.join(t.root(word) for word in sentence.strip().split())