题解 | 编辑距离(一) 忘记初始化
编辑距离(一)
https://www.nowcoder.com/practice/6a1483b5be1547b1acd7940f867be0da
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str1 string字符串 * @param str2 string字符串 * @return int整型 */ public int editDistance (String str1, String str2) { // write code here int m = str1.length(), n = str2.length(); int dp[][] = new int[m + 1][n + 1]; // init for (int i = 1; i <= m; i++) { dp[i][0] = dp[i - 1][0] + 1; } for (int i = 1; i <= n; i++) { dp[0][i] = dp[0][i - 1] + 1; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { int min = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1; // 插入 if (str1.charAt(i - 1) == str2.charAt(j - 1)) { dp[i][j] = Math.min(dp[i - 1][j - 1], min); } else { dp[i][j] = Math.min(dp[i - 1][j - 1] + 1, min); // 修改 } } } return dp[m][n]; } }