LeetCode题目72. 编辑距离
给定两个单词 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’)
解题思路
思路:动态规划思想,建立一个(m+1)x(n+1)的数组dp,其中dp[i][j]代表str1中0i-1的子串到str2中的0j-1的所需编辑次数。
则dp[i][j]的值来源于以下四种情况:(ip:插入一个字符的代价 dp:删除一个字符的代价 rp:替换一个字符的代价)
(1) str1[0…i-1]先变为str1[0…i-2],再由str1[0…i-2]变为str2[0…j-1],即dp[i][j]=dp+dp[i-1][j];
(2) str1[0…i-1]先变为str2[0…j-2],再由str2[0…j-2]变为str2[0…j-1],即dp[i][j]=ip+dp[i][j-1];
(3)
(i)当str1[i-1]==str2[j-1],只需要将str1[0…i-2]先变为str2[0…j-2],即dp[i][j]=dp[i-1][j-1];
(ii)当str1[i-1]!=str2[j-1],先将str1[i-1]交换为str2[j-1],再将str1[0…i-2]先变为str2[0…j-2],即dp[i][j]=rp+dp[i-1][j-1];
dp[i][j]取上述四种情况的最下值。
完整代码
class Solution {
public int minDistance(String word1, String word2) {
if(word1==null||word2==null)return -1;
if(word1.length()==0) return word2.length();
if(word2.length()==0) return word1.length();
int m=word1.length();
int n=word2.length();
//删除代价
int rp=1;
//交换代价
int sp=1;
//增加代价
int ip=1;
int[][] dp=new int[m+1][n+1];
for(int i=1;i<=m;i++)
dp[i][0]=i;
for(int j=1;j<=n;j++)
dp[0][j]=j;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++)
{
int t1=rp+dp[i-1][j];
int t2=ip+dp[i][j-1];
int t3=0;
if(word1.charAt(i-1)==word2.charAt(j-1))
t3=dp[i-1][j-1];
else
t3=sp+dp[i-1][j-1];
dp[i][j]=Math.min(Math.min(t1,t2),t3);
}
}
return dp[m][n];
}
}
更多LeetCode题目及答案解析见GitHub: https://github.com/on-the-roads/LeetCode
剑指offer题目及答案解析:https://github.com/on-the-roads/SwordToOffer