题目描述(Hard)
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
题目链接
https://leetcode.com/problems/edit-distance/description/
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
算法分析
动态规划法:设状态为f[i][j] ,表示A[0,i-1] 和B[0,j-1] 之间的最小编辑距离。设A[0,i-1] 的形式是str1c,B[0,j-1] 的形式是str2d,
1. 如果 c==d,则f[i][j]=f[i-1][j-1] ;
2. 如果 c!=d,
(a) 如果将c 替换成d,则f[i][j]=f[i-1][j-1]+1;
(b) 如果在c 后面添加一个d,则f[i][j]=f[i][j-1]+1;
(c) 如果将c 删除,则f[i][j]=f[i-1][j]+1;
提交代码:
class Solution {
public:
int minDistance(string word1, string word2) {
const int m = word1.size();
const int n = word2.size();
int f[m + 1][n + 1];
for (int i = 0; i <= m; ++i)
f[i][0] = i;
for (int j = 0; j <= n; ++j)
f[0][j] = j;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (word1[i - 1] == word2[j - 1])
f[i][j] = f[i - 1][j - 1];
else {
// 删除 or 添加
int dis = min(f[i][j - 1], f[i - 1][j]);
// 替换 or Others
f[i][j] = min(dis, f[i - 1][j - 1]) + 1;
}
}
}
return f[m][n];
}
};