#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; }
最小编辑距离问题
最新推荐文章于 2024-07-12 18:56:03 发布