LeetCode 648 单词替换题解

LeetCode 648 单词替换题解

题目描述

题目链接

在英语中,我们有一个叫做「词根」的概念,可以缩短其他单词的长度。给定一个词典和一句话,将句子中的所有单词用其最短匹配词根替换。

解题思路

哈希表 + 前缀匹配法

  1. 预处理词典:将词典存入哈希表实现O(1)查找
  2. 最短匹配优先:对每个单词检查所有可能前缀
  3. 动态替换:找到第一个匹配的前缀立即替换

代码实现

python 复制代码
from typing import List

class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        # 将词典存入集合实现快速查找(O(1)时间复杂度)
        root_set = set(dictionary)  # 空间复杂度 O(n)
        
        # 分割句子为单词列表(O(m)时间复杂度,m为单词数)
        words = sentence.split()
        
        # 遍历每个单词进行替换(O(m*l)时间复杂度,l为单词平均长度)
        for i in range(len(words)):
            # 检查所有可能前缀(从最短开始)
            for j in range(1, len(words[i])):  # 注意:词根至少1个字符
                # 发现匹配立即替换并终止检查
                if words[i][:j] in root_set:
                    words[i] = words[i][:j]
                    break  # 保证替换最短匹配词根
        
        # 重新组合为句子(O(m)时间复杂度)
        return ' '.join(words)
if __name__ == "__main__":
    # 测试用例
    test1 = Solution().replaceWords(["cat", "bat", "rat"], "the cattle was rattled by the battery")  # "the cat was rat by the bat"
    test2 = Solution().replaceWords(["a", "b", "c"], "aadsfasf absbs bbab cadsfafs")  # "a a b c"
    print(test1)  # 输出:"the cat was rat by the bat"
    print(test2)  # 输出:"a a b c"
相关推荐
小羊在睡觉5 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
3DVisionary5 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
jiayong235 小时前
面试中遇到不熟悉问题的应对策略深度解析
面试·职场和发展
好评笔记5 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466855 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
sheeta19986 小时前
LeetCode 每日一题笔记 日期:2026.05.29 题目:3300. 最小元素
笔记·leetcode
_日拱一卒6 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
珂朵莉MM6 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--束搜索
人工智能·算法
Omics Pro7 小时前
首个!外源天然产物综合性代谢图谱
数据库·人工智能·算法·机器学习·r语言
JAVA社区7 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展