From 4291679c21575f938b63061bcb80739769fc47d6 Mon Sep 17 00:00:00 2001 From: weikunkun Date: Fri, 14 May 2021 17:08:19 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00072.=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E8=B7=9D=E7=A6=BB=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...26\350\276\221\350\267\235\347\246\273.md" | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git "a/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" "b/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" index 7e27a3d562..32c888f125 100644 --- "a/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" +++ "b/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" @@ -198,7 +198,32 @@ public: Java: - +```java +public int minDistance(String word1, String word2) { + int m = word1.length(); + int n = word2.length(); + 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++) { + // 因为dp数组有效位从1开始 + // 所以当前遍历到的字符串的位置为i-1 | j-1 + if (word1.charAt(i - 1) == word2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1; + } + } + } + return dp[m][n]; +} +``` Python: