mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-04 19:28:07 +08:00
【72. 编辑距离】【Python】
【72. 编辑距离】【Python】
This commit is contained in:
@ -291,4 +291,31 @@ class Node {
|
||||
<img src="../pictures/qrcode.jpg" width=200 >
|
||||
</p>
|
||||
|
||||
======其他语言代码======
|
||||
======其他语言代码======
|
||||
[ChenjieXu](https://github.com/ChenjieXu) 提供Python版本代码:
|
||||
|
||||
```python3
|
||||
def minDistance(word1, word2):
|
||||
m, n = len(word1), len(word2)
|
||||
# 创建 DP 数组
|
||||
dp = [[0] * (n + 1) for _ in range(m + 1)]
|
||||
|
||||
# base case初始化
|
||||
for i in range(m + 1):
|
||||
dp[i][0] = i
|
||||
for j in range(n + 1):
|
||||
dp[0][j] = j
|
||||
|
||||
# 自底向上求解
|
||||
for i in range(1, m + 1):
|
||||
for j in range(1, n + 1):
|
||||
# 状态转移方程
|
||||
if word1[i - 1] == word2[j - 1]:
|
||||
dp[i][j] = dp[i - 1][j - 1]
|
||||
else:
|
||||
dp[i][j] = min(dp[i - 1][j] + 1,
|
||||
dp[i][j - 1] + 1,
|
||||
dp[i - 1][j - 1] + 1)
|
||||
# 储存着整个 word1 和 word2 的最小编辑距离
|
||||
return dp[m][n]
|
||||
````
|
Reference in New Issue
Block a user