题目链接
这是道比较经典的动态规划题。
状态转移方程:
对于字符串x,y,编辑距离E(i,j)为
E(i,j) = min(1 + E(i-1,j), 1 + E(i,j-1), diff(i,j) + E(i-1,j-1))
diff(i,j) = if x[i] == y[j] then 0 else 1
初始状态:
E(0,i) = E(j,0) = 0
伪代码是
for i = 0,1,2,...,m:
E(i,0) = i
for j = 1,2,...,m:
E(0,j) = j
for i = 1,2,...,m:
for j = 1,2,...,n:
diff(i,j) = if x[i] == y[j] then 0 else 1
E(i,j) = min(1 + E(i-1,j), 1 + E(i,j-1), diff(i,j) + E(i-1,j-1))
容易看出复杂度是O(mn)的
c++代码实现:
class Solution {
public:
int minDistance(string word1, string word2) {
int r = word1.length() + 1;
int c = word2.length() + 1;
int **E = new int*[r];
for(int i = 0; i < r; i++){
E[i] = new int[c];
for(int j = 0; j < c; j++){
E[i][j] = 0;
}
}
for(int i = 0; i < r; i++){
E[i][0] = i;
}
for(int j = 0; j < c; j++){
E[0][j] = j;
}
for(int i = 1; i < r; i++){
for(int j = 1; j < c; j++){
E[i][j] = min(min(1+E[i-1][j],1+E[i][j-1]), int(!(word1[i-1] == word2[j-1])) + E[i-1][j-1]);
}
}
return E[r-1][c-1];
}
};
因为字符数组下标从0开始,其中转化走了一些弯路。
提交结果如下: