# 30 Day Challenge Day 22 | Leetcode 72. Edit Distance

## 题解

Hard

Example: word1: abc, word2: abbc
\0 a b b c
\0  0 1 2 3 4
a  1 0 1 2 3
b  2 1 0 1 2
c  3 2 1 1 1

DP:
state:
dp[i][j] word1[0-i] --> word2[0-j]
initialization:
1st row: dp[0][j] = j;
1st col: dp[i][0] = i;
transition:
case: word1[i-1] == word2[j-1] ==> dp[i][j] = dp[i-1][j-1]
case: word1[i-1] != word2[j-1] ==> dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + 1  <== missing dp[i-1][j-1]
delete      insert                       replace
result:
dp[m][n]
*****/
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(), n = word2.size();

vector<vector<int>> dp(m+1, vector<int>(n+1, 0));

// initialization

for(int i = 0; i <= m; i++) {
dp[i][0] = i;
}

for(int j = 0; j <= n; j++) {
dp[0][j] = j;
}

// state transition
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
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], min(dp[i-1][j], dp[i][j-1])) + 1;
}
}
}

return dp[m][n];
}
};
posted @ 2020-10-10 02:57  CasperWin  阅读(97)  评论(0编辑  收藏  举报