LeetCode 题解工作台

编辑距离

给你两个单词 word1 和 word2 , 请返回将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 示例 1: 输入: word1 = "horse", word2 = "ros" 输出: 3 解释: hors…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示将 的前 个字符转换成 的前 个字符所使用的最少操作数。初始时 $f[i][0] = i$, $f[0][j] = j$。其中 $i \in [1, m], j \in [0, n]$。 考虑 :

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个单词 word1 和 word2请返回将 word1 转换成 word2 所使用的最少操作数  。

你可以对一个单词进行如下三种操作:

  • 插入一个字符
  • 删除一个字符
  • 替换一个字符

 

示例 1:

输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

示例 2:

输入:word1 = "intention", word2 = "execution"
输出:5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

 

提示:

  • 0 <= word1.length, word2.length <= 500
  • word1word2 由小写英文字母组成
lightbulb

解题思路

方法一:动态规划

我们定义 f[i][j]f[i][j] 表示将 word1word1 的前 ii 个字符转换成 word2word2 的前 jj 个字符所使用的最少操作数。初始时 f[i][0]=if[i][0] = i, f[0][j]=jf[0][j] = j。其中 i[1,m],j[0,n]i \in [1, m], j \in [0, n]

考虑 f[i][j]f[i][j]

  • 如果 word1[i1]=word2[j1]word1[i - 1] = word2[j - 1],那么我们只需要考虑将 word1word1 的前 i1i - 1 个字符转换成 word2word2 的前 j1j - 1 个字符所使用的最少操作数,因此 f[i][j]=f[i1][j1]f[i][j] = f[i - 1][j - 1]
  • 否则,我们可以考虑插入、删除、替换操作,那么 f[i][j]=min(f[i1][j],f[i][j1],f[i1][j1])+1f[i][j] = \min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1

综上,我们可以得到状态转移方程:

f[i][j]={i,if j=0j,if i=0f[i1][j1],if word1[i1]=word2[j1]min(f[i1][j],f[i][j1],f[i1][j1])+1,otherwisef[i][j] = \begin{cases} i, & \textit{if } j = 0 \\ j, & \textit{if } i = 0 \\ f[i - 1][j - 1], & \textit{if } word1[i - 1] = word2[j - 1] \\ \min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1, & \textit{otherwise} \end{cases}

最后,我们返回 f[m][n]f[m][n] 即可。

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别是 word1word1word2word2 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m, n = len(word1), len(word2)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        for j in range(1, n + 1):
            f[0][j] = j
        for i, a in enumerate(word1, 1):
            f[i][0] = i
            for j, b in enumerate(word2, 1):
                if a == b:
                    f[i][j] = f[i - 1][j - 1]
                else:
                    f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1
        return f[m][n]
speed

复杂度分析

指标
时间complexity is O(m _n) because each subproblem dp[i][j] is computed once, iterating through all i x j combinations. Space complexity is O(m_ n) for the full DP table, or O(min(m,n)) if optimized to store only one previous row, which is critical for long strings.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks how the DP table represents overlapping subproblems and why it's necessary.

  • question_mark

    Checks if you can optimize space for large input strings up to 500 characters.

  • question_mark

    Inquires about handling equal characters and how it affects the state transition.

warning

常见陷阱

外企场景
  • error

    Failing to initialize base cases correctly, leading to off-by-one errors in dp[0][j] or dp[i][0].

  • error

    Confusing insertion and deletion operations, which can produce incorrect minimal edits.

  • error

    Attempting recursive solutions without memoization, causing exponential time complexity and timeouts.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute edit distance with only insertions and deletions allowed, ignoring replacements.

  • arrow_right_alt

    Find all sequences of operations that achieve the minimum edit distance.

  • arrow_right_alt

    Apply edit distance to detect approximate string matching in a text or DNA sequence.

help

常见问题

外企场景

编辑距离题解:状态·转移·动态规划 | LeetCode #72 中等