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"
相关推荐
vibecoding日记11 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr213813 小时前
Verilog参数化游程编码RLE模块
算法
望易13 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络17 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术2 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望2 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法