# 插入、删除、修改操作 代价不等的 最短编辑距离 动态规化求法

MED：最小的编辑距离(Minimum Edit Distance)

1.删除strA[i]，此时等价于要计算MED{ strA[0…i-1], strB[0…j] }，显然，这就是C[i-1][j]，此时C[i][j] = C[i-1][j] + cost_Del。

2.删除strB[j]，此时等价于要计算MED{ strA[0…i], strB[0…j-1] }，显然，这就是此时C[i][j] = C[i][j-1] + cost_Del。

3.将strA[i]修改为strB[j]，此时等价于要计算MED{ strA[0…i-1], strB[0…j-1] }，显然，此时C[i][j] = C[i-1][j-1] + cost_Edit。

4.将strB[j]修改为strA[i]，此时等价于要计算MED{ strA[0…i-1], strB[0…j-1] }，显然，此时C[i][j] = C[i-1][j-1] + cost_Edit。

5.将strB[j]添加到strA[i]之后，此时等价于要计算MED{ strA[0…i], strB[0…j-1] }，显然，此时C[i][j] = C[i][j-1] + cost_Insert。

6.将strA[i]添加到strB[j]之后，此时等价于要计算MED{ strA[0…i-1], strB[0…j] }，显然，此时C[i][j] = C[i-1][j] + cost_Insert。

``````if(strA[i-1] == strB[j-1])
C[i][j] = C[i-1][j-1];
else
{
int C1 = C[i-1][j] + cost_Del;
int C2 = C[i][j-1] + cost_Del;
int C3 = C[i][j-1] + cost_Insert;
int C4 = C[i-1][j] + cost_Insert;
int C5 = C[i-1][j-1] + cost_Edit;
C[i][j] = std::min(C1, C2, C3, C4, C5);
}``````

``````if(strA[i-1] == strB[j-1])
C[i&1][j] = C[(i-1)&1][j-1];
else
{
int C1 = C[(i-1)&1][j] + cost_Del;
int C2 = C[i&1][j-1] + cost_Del;
int C3 = C[i&1][j-1] + cost_Insert;
int C4 = C[(i-1)&1][j] + cost_Insert;
int C5 = C[(i-1)&1][j-1] + cost_Edit;
C[i][j] = std::min(C1, C2, C3, C4, C5);
}``````

leetcode上有类似的题，不过它默认是所有操作的代价都是相等的。所以只用比较三个值的大小即可。

https://leetcode.com/problems/edit-distance/

``````class Solution {
public:
int minDistance(const string& word1, const string& word2) {
int len1 = word1.size();
int len2 = word2.size();
if(0 == len1)
return len2;
else if(0 == len2)
return len1;
for(int j = 0; j <= len2; j++)
C[0][j] = j;

for(int i = 1; i < len1+1; i++)
{
C[(i-1)&1][0] = i-1;
C[i&1][0] = i;
for(int j = 1; j < len2 + 1; j++)
if(word1[i-1] == word2[j-1])
C[i&1][j] = C[(i-1)&1][j-1];
else
{
int C1 = C[(i-1)&1][j-1] + 1;
int C2 = C[i&1][j-1] + 1;
C2 = C2 < C1? C2: C1;
int C3 = C[(i-1)&1][j] + 1;
C[i&1][j] = C3 < C2? C3 : C2;
}
}
return C[len1&1][len2];
}

private:
int C[2][1000];
};``````

本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。