题解 | #计算字符串的编辑距离#
计算字符串的编辑距离
https://www.nowcoder.com/practice/3959837097c7413a961a135d7104c314
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int LevenshteinDistance(string str1, string str2) {
int m = str1.size();
int n = str2.size();
vector<vector<int>> lev(m + 1, vector<int>(n + 1));
for (int j = 0; j <= n; j++) {
lev[0][j] = j;
}
for (int i = 0; i <= m; i++) {
lev[i][0] = i;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
lev[i][j] = min(lev[i][j - 1] + 1, lev[i - 1][j] + 1);
if (str1[i - 1] == str2[j - 1]) {
lev[i][j] = min(lev[i][j], lev[i - 1][j - 1]);
} else {
lev[i][j] = min(lev[i][j], lev[i - 1][j - 1] + 1);
}
}
}
return lev[m][n];
}
int main() {
string str1, str2;
cin >> str1 >> str2;
int distance = LevenshteinDistance(str1, str2);
cout << distance;
}
