操作名称:删除、插入、替换
    编辑距离:编辑操作的数量

    将单词kittchen通过编辑操作变成sitting
    方案一:kittchen-sittchen-sitthen-sitten-sittn-sittin-sitting<编辑六次:编辑距离为6>
    方案二:kittchen-sittchen-sitthen-sitten-sittin-sitting<编辑距离5>

    问题描述:Minimum Edit Distance,MED
    输入:
    长度为n的字符串,长度为m的字符串t
    输出:
    求出一组编辑操作O=零|O|最小,s经过O操作使得s=t

    image.png
    image.png
    image.pngimage.png

    1. #include<iostream>
    2. using namespace std;
    3. /*
    4. 操作名称:删除、插入、替换
    5. 编辑距离:编辑操作的数量
    6. 将单词kittchen通过编辑操作变成sitting
    7. 方案一:kittchen-sittchen-sitthen-sitten-sittn-sittin-sitting<编辑六次:编辑距离为6>
    8. 方案二:kittchen-sittchen-sitthen-sitten-sittin-sitting<编辑距离5>
    9. 问题描述:Minimum Edit Distance,MED
    10. 输入:
    11. 长度为n的字符串,长度为m的字符串t
    12. 输出:
    13. 求出一组编辑操作O=<e1,e2,e3.....en>零|O|最小,s经过O操作使得s=t
    14. */
    15. void Print_MED(char Rec[][7],char s[],char t[], int i, int j) {
    16. if (i == 0 && j == 0)
    17. return;
    18. if (Rec[i][j] == 'LU') {
    19. Print_MED(Rec, s, t, i - 1, j - 1);
    20. if (s[i] == t[j])
    21. cout << "无需操作!" << endl;
    22. else
    23. cout << "用t[" << j << "]替换s[" << i << "]\n";
    24. }
    25. else if (Rec[i][j] == 'U') {
    26. Print_MED(Rec, s, t, i - 1, j);
    27. cout << "删除s[" << i << "]\n";
    28. }
    29. else {
    30. Print_MED(Rec, s, t, i , j- 1);
    31. cout << "插入t[" << j << "]\n";
    32. }
    33. }
    34. int main() {
    35. char s[] = "OABCBDAB", t[] = "OBDCABA";
    36. const int n = 7, m = 6;
    37. int Dp[n+1][m+1] = {};
    38. char Rec[n+1][m+1];
    39. //init
    40. for (int i = 0; i <= n; i++) {
    41. Dp[i][0] = i;
    42. Rec[i][0] = 'U';
    43. }
    44. for (int i = 0; i <= m; i++) {
    45. Dp[0][i] = i;
    46. Rec[0][i] = 'L';
    47. }
    48. int c;
    49. //动态规划
    50. for (int i = 1; i <= n; i++){
    51. for (int j = 1; j <= m; j++) {
    52. c = 0;
    53. if (s[i] != t[j])
    54. c = 1; //辅助替换
    55. int Replace = Dp[i - 1][j - 1] + c; //替换
    56. int Delete = Dp[i - 1][j] + 1; //删除
    57. int Insert = Dp[i][j - 1] + 1; //插入
    58. int min = Replace;
    59. min = min < Delete ? min : Delete;
    60. min = min < Insert ? min : Insert;
    61. if (min== Replace) {
    62. Dp[i][j] = Replace; //根据递推公式构造Dp数组
    63. Rec[i][j] = 'LU';
    64. }
    65. else if (min == Delete) {
    66. Dp[i][j] = Delete;
    67. Rec[i][j] = 'U';
    68. }
    69. else {
    70. Dp[i][j] = Insert;
    71. Rec[i][j] = 'L';
    72. }
    73. }
    74. }
    75. for (int i = 0; i <= n; i++) {
    76. for (int j = 0; j <= m; j++)
    77. cout << Dp[i][j] << " ";
    78. cout << endl;
    79. }
    80. cout << endl << "最短编辑距离为:" << Dp[n][m] << endl;
    81. //追踪最优方案:(还有问题)
    82. //Print_MED(Rec, s, t, n, m);
    83. }