Problem: 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
用矩阵表示字符的含义可以复习一下上一题 Interleaving String
这一题,还是以下面的图来进行说明:
图中表示的是,将Park变成Spake的最小距离,假设Park为String1,Spake为String2
dp[i][j] 表示从String1的前i位,变到String2的前j位,最小需要多少改变
比如我们看矩阵的第一行,分别代表从" "(空字符)变到"s", 变到"sp",变到"spa",变到"spak",变到"spake" 需要多少次改变,因为每次只能选择往上添加一个字符,所以累加操作数分别为1,2,3,4,5
同理,矩阵的第一列分别代表从"p" 变到” “(空字符),从”pa“变空,从”par“变空,从"park"变空需要多少次改变,因为每次只能选择删去一个字符,所以累加操作数分别为1,2,3,4
那好,我们再举个例子,看图中绿色字体的那个例子
下箭头: 我们现在已经知道了从" " 到”s“的距离,那么从"p" 到''s" 我们只要删去这个p就行了 (Delete)
右箭头: 我们现在已经知道了从”p“到" "的距离,那么从"p" 到"s" 我们只要插入这个s就行了 (Insert)
右下箭头: 我们现在已经知道了从" "到" "的距离,那么从"p" 到"s" 我们只需要把p替换成s就行了(Replace)
注意替换的时候,如果i所代表的的字符 == j所代表的字符,那么我们便不需要做任何多余的操作(No Operation)
代码如下:
public class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m+1][n+1];
dp[0][0] = 0;
for(int i=1;i<=m;i++)
dp[i][0] = dp[i-1][0] + 1;
for(int j=1;j<=n;j++)
dp[0][j] = dp[0][j-1] + 1;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++){
if (word1.charAt(i-1)==word2.charAt(j-1))
dp[i][j] = dp[i-1][j-1];
else dp[i][j] = 1 + Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1]));
}
return dp[m][n];
}
}