最小编辑距离问题

#include<iostream>
#include<vector>
using namespace std;
vector<vector<string>> Rec;
int minDistance(string word1, string word2) {
    int n = word1.size();
    int m = word2.size();
    int c = 0;
    int replace = 0;
    int delete_ = 0;
    int insert = 0;
     Rec.resize(n + 1, vector<string>(m + 1));
    vector<vector<int>> D(n + 1, vector<int>(m + 1, 0));
    for (int i = 0; i <= n; ++i) {
        D[i][0] = i;
    }
    for (int j = 0; j <= m; ++j) {
        D[0][j] = j;
    }
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            if (word1[i - 1] != word2[j - 1]) {
                c = 1;
            } else {
                c = 0;
            }

            replace = D[i - 1][j - 1] + c;
            delete_ = D[i - 1][j] + 1;
            insert = D[i][j - 1] + 1;
            D[i][j] = min(replace, min(delete_, insert));
            if (D[i][j] == replace) {
                Rec[i][j] = "LU";
            } else if (D[i][j] == delete_) {
                Rec[i][j] = "U";
            } else {
                Rec[i][j] = "L";
            }

        }
    }
    return D[n][m];
}
void printMED (vector<vector<string>>& Rec, string word1, string word2, int i, int j) {
    if (i == 0 && j == 0) {
        return;
    }
    if (Rec[i][j] == "LU") {
        printMED(Rec, word1, word2, i - 1, j - 1);
        if(word1[i - 1] != word2[j - 1])
            cout << "Replace " << word1[i - 1] << " with " << word2[j - 1] << endl;


    } else if (Rec[i][j] == "U") {
        printMED(Rec, word1, word2, i - 1, j);
        cout << "Delete " << word1[i - 1] << endl;
    } else {
        printMED(Rec, word1, word2, i, j - 1);
        cout << "Insert " << word2[j - 1] << endl;
    }
}

int main() {
//测试
    string word1 = "horse";
    string word2 = "ros";
    cout << minDistance(word1, word2) << endl;
    printMED(Rec, word1, word2, word1.size(), word2.size());


    return 0;
}
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值