The edit distance between two strings is the minimum changes required to make two strings identical.
There can be three operations
#include <iostream>
#include <string>
using namespace std;
int min (int a, int b, int c) {
int m = a;
if (a > b) {
m = b;
}
if (c > m) {
return m;
} else {
return c;
}
}
int editDistance (string s1, string s2, int m, int n) {
int dp[m+1][n+1];
for (int i = 0; i<= m; i++) {
for (int j = 0; j <=n ; j++) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else if (s1[i-1] == s2[j-1]) {
dp[i][j] = dp[i-1][j-1];
} else {
dp[i][j] = 1 + min (dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
}
}
}
return dp[m][n];
}
int main() {
string str1 = "mist";
string str2 = "misty";
cout << editDistance(str1, str2, str1.length(), str2.length());
return 0;
}
There can be three operations
- Insertion of character
- Deletion of character
- Replace the character
#include <iostream>
#include <string>
using namespace std;
int min (int a, int b, int c) {
int m = a;
if (a > b) {
m = b;
}
if (c > m) {
return m;
} else {
return c;
}
}
int editDistance (string s1, string s2, int m, int n) {
int dp[m+1][n+1];
for (int i = 0; i<= m; i++) {
for (int j = 0; j <=n ; j++) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else if (s1[i-1] == s2[j-1]) {
dp[i][j] = dp[i-1][j-1];
} else {
dp[i][j] = 1 + min (dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
}
}
}
return dp[m][n];
}
int main() {
string str1 = "mist";
string str2 = "misty";
cout << editDistance(str1, str2, str1.length(), str2.length());
return 0;
}
No comments:
Post a Comment