0
点赞
收藏
分享

微信扫一扫

Leetcode 648. 单词替换 (split, join, map的应用)

慕容冲_a4b8 2022-01-06 阅读 68

直接暴力判断替换法:

class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        rootset = set(dictionary)

        def replace(word):
            for i in range(1, len(word)):
                if word[:i] in rootset:
                    return word[:i]
            return word

        return " ".join(map(replace, sentence.split()))

使用Trie树优化方法
 

class Trie:
    def __init__(self):
        self.child = [None] * 26
        self.isend = False  

    def insert(self, word: str) -> None:
        root = self
        for c in word:
            idx = ord(c) - ord('a')
            if root.child[idx] == None:
                root.child[idx] = Trie()
            root = root.child[idx]
        root.isend = True
    
    def find(self, word: str) -> str:
        root = self
        #   用来计数前缀字符数量
        i = 0
        for c in word:
            idx = ord(c) - ord('a')
            #   没有前缀直接返回 word
            if root.child[idx] == None:
                return word
            root = root.child[idx]
            i += 1
            #   匹配到了词根的末尾,直接退出
            if root.isend == True:
                break
        return word[: i]

class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        T = Trie()
        for word in dictionary:
            T.insert(word)

        return " ".join(map(T.find, sentence.split()))
举报

相关推荐

0 条评论