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"
相关推荐
hold?fish:palm42 分钟前
45 二叉树的右视图
开发语言·c++·算法
粤鼎恒业1 小时前
惠州工厂电子料回收厂家推荐:从交接单反推筛选标准
大数据·数据库·算法·硬件架构·硬件工程·pcb工艺·材料工程
小爷毛毛(卓寿杰)1 小时前
【Agent 意图识别】输出协议、评估与置信度
人工智能·算法·大模型·prompt·大语言模型·agent
优质酸酸乳1 小时前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光2 小时前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控
旋生万物2 小时前
Agent System Prompt 注入螺旋公理:让 AI 推理不跑偏的可复制模板(附完整 Prompt)
人工智能·算法
深圳雨林凯AI2 小时前
图案裂变的空间关系原理:元素放大为何必然挤压负空间,以及三个可调变量|雨林凯AI技术拆解
人工智能·算法
tellmewhoisi2 小时前
机器学习:聚类算法
算法·机器学习·聚类
yi0113 小时前
LeetCode 134 加油站:从 双循环暴力 演变到 贪心
linux·算法·leetcode
sogw-三叶草️3 小时前
LeetCode 989. 数组形式的整数加法
数据结构·算法