Skip to content

Commit d6ab9bb

Browse files
committed
增加编辑距离解法代码
1 parent e364525 commit d6ab9bb

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

动态规划系列/编辑距离.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,38 @@ class Node {
262262

263263
![labuladong](../pictures/labuladong.png)
264264

265-
Jinglun Zhou 提供C++解法代码:
265+
[labuladong](https://github.com/labuladong) 提供Java解法代码:
266+
267+
```
268+
int minDistance(String s1, String s2) {
269+
int m = s1.length(), n = s2.length();
270+
int[][] dp = new int[m + 1][n + 1];
271+
// base case
272+
for (int i = 1; i <= m; i++)
273+
dp[i][0] = i;
274+
for (int j = 1; j <= n; j++)
275+
dp[0][j] = j;
276+
// 自底向上求解
277+
for (int i = 1; i <= m; i++)
278+
for (int j = 1; j <= n; j++)
279+
if (s1.charAt(i-1) == s2.charAt(j-1))
280+
dp[i][j] = dp[i - 1][j - 1];
281+
else
282+
dp[i][j] = min(
283+
dp[i - 1][j] + 1,
284+
dp[i][j - 1] + 1,
285+
dp[i-1][j-1] + 1
286+
);
287+
// 储存着整个 s1 和 s2 的最小编辑距离
288+
return dp[m][n];
289+
}
290+
291+
int min(int a, int b, int c) {
292+
return Math.min(a, Math.min(b, c));
293+
}
294+
```
295+
296+
[Jinglun Zhou](https://github.com/Jasper-Joe) 提供C++解法代码:
266297

267298
```CPP
268299

0 commit comments

Comments
 (0)