简繁EN

LeetCodeNo. 091

[LeetCode with Python] 72. Edit Distance

Contents

Problem

Problem page: https://leetcode.com/problems/edit-distance/
Topics: Dynamic Programming, String
Difficulty: Hard
Similar problems: (M) One Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character


Analysis

This is a classic dynamic programming problem. Nine times out of ten, you can improve the space complexity of a DP solution. You don't really need to allocate a whole (m+1)(n+1) matrix. The solution I'm using is down to two rows. You can cut that to one row (plus a variable to hold the value from the upper left), but you can't get it down to a 22 matrix: each cell needs the value in the same column of the previous row, so until you finish the current row, you still need to keep the remaining cells of the previous row.
Each cell in this DP matrix represents an optimal solution to the current subproblem. If each cell records which smaller subproblem's optimal solution it was built from, you can start at a given cell and follow those records back to trace the full path that makes up that cell's solution. If there's more than one optimal solution, the paths form a tree.
Row 0 and column 0 of a DP matrix usually need special handling.
For DP problems, it's also worth getting into the habit of writing out the recurrence because the formulas explain the idea more concisely:

  1. d[0, j] = j
  2. d[i, 0] = i
  3. d[i, j] = d[i-1, j - 1] if A[i] == B[j]
  4. d[i, j] = min(d[i-1, j - 1], d[i, j - 1], d[i-1, j]) + 1 if A[i] != B[j]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
# @return an integer
def minDistance(self, word1, word2):
if "" == word1 and "" == word2:
return 0
elif "" == word1:
return len(word2)
elif "" == word2:
return len(word1)
len1 = len(word1)
len2 = len(word2)
arr1 = [0 for y in range(0, len1 + 1)]
arr2 = [0 for y in range(0, len1 + 1)]
arr1[0] = 0
for y in range(1, len1 + 1):
arr1[y] = y
for x in range(1, len2 + 1):
arr2[0] = x
for y in range(1, len1 + 1):
arr2[y] = min(arr1[y - 1] + (0 if (word1[y - 1] == word2[x - 1]) else 1), arr1[y] + 1, arr2[y - 1] + 1)
tmp = arr1
arr1 = arr2
arr2 = tmp
for y in range(0, len1 + 1):
arr2[y] = 0
return arr1[len1]

Article link: https://xnerv.wang/en/leetcode-edit-distance/