一、题目
1、审题
2、分析
给出两个单词字符串,word1 经过字符的删除、替换、插入,最少需要几步才能变为 word2.
二、解答
1、思路:
f(i, j) 代表 word1 的前 i 个字符与 word2 的前 j 个字符的最小代价:
①、若 word1[i] == word2[j],则 f(i, j) = f(i-1, j-1).
②、若 word1[i] != word2[j],则 f(i, j) = 1 + Min(f(i-1, j) , f(i, j-1), f(i-1, j-1) );
其中 f(i-1, j), 代表word1删除第 i 个字符;
f(i, j-1) 代表 word1 插入一个字符;
f(i-1, j-1) 代表 word1 替换第 i 个字符
public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] cost = new int[m+1][n+1]; // 代价 for (int i = 0; i < m; i++) // cost[i][0] = i; // word1 的前 i 个字符 删除操作 for (int i = 0; i < n; i++) cost[0][i] = i; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if(word1.charAt(i) == word2.charAt(j)) cost[i+1][j+1] = cost[i][j]; else { int a = cost[i][j]; int b = cost[i][j+1]; int c = cost[i+1][j]; // 找最小代价 cost[i+1][j+1] = 1 + Math.min(Math.min(a, b), c); } } } return cost[m][n]; }
2、答案链接:
https://leetcode.com/problems/edit-distance/discuss/25849/Java-DP-solution-O(nm)