字典树-648. 单词替换-PYTHON

在这里插入图片描述

前缀哈希

class Solution(object):
    def replaceWords(self, dict, sentence):
        """
        :type dict: List[str]
        :type sentence: str
        :rtype: str
        """
        rootset = set(dict) #将所有单词存入集合,去重,方便存取

        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()))

字典树

class TrieNode:
    def __init__(self, val=None, isEnd=False):
        self.val = val
        self.isEnd = isEnd
        self.children = {} #子字典树

class Solution:
    def replaceWords(self, dict, sentence):
        def insertWord(word):
            cur = root #重置跟踪指针
            for w in word:#逐字母插入字典树
                if w not in cur.children:
                    cur.children[w] = TrieNode(w, False)
                cur = cur.children[w] #切换跟踪指针
            cur.isEnd = True
        
        def find(word):#查找是否存在词根可以替换
            cur = root  #重置跟踪指针
            res = []
            for w in word:
                if cur.isEnd:#在有词根可以替换的条件下,遇到结束符号将现有词根返回
                    return ''.join(res) 
                if w not in cur.children:#没有匹配到相应词根,返回原词
                    return word
                res.append(w) #将匹配到的字母暂时放置在res中
                cur = cur.children[w] #切换跟踪指针到子字典树中
            else: #此用法,当for正常结束后会执行else,for中如果break了就不会执行else了,这是单词与词根同词的情况,不能通过for中的return进行返回,就需要另外的return分支了
                return ''.join(res)

        root = TrieNode('')
        for word in dict: #遍历词根,插入字典中
            insertWord(word)

        #替换操作
        words = sentence.split() #将句子按空格切分
        res = []
        for word in words:
            res.append(find(word))
        return ' '.join(res)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值