TheAlgorithms-C-Plus-Plus/dynamic_programming/Edit Distance.cpp

95 lines
2.2 KiB
C++
Raw Normal View History

2017-10-28 18:06:20 +08:00
/* Given two strings str1 & str2
* and below operations that can
* be performed on str1. Find
* minimum number of edits
* (operations) required to convert
* 'str1' into 'str2'/
* a. Insert
* b. Remove
* c. Replace
* All of the above operations are
* of equal cost
*/
#include <iostream>
#include <string>
using namespace std;
2019-08-21 10:10:08 +08:00
int min(int x, int y, int z)
{
return min(min(x, y), z);
2017-10-28 18:06:20 +08:00
}
/* A Naive recursive C++ program to find
* minimum number of operations to convert
* str1 to str2.
* O(3^m)
*/
2019-08-21 10:10:08 +08:00
int editDist(string str1, string str2, int m, int n)
{
if (m == 0)
return n;
if (n == 0)
return m;
2017-10-28 18:06:20 +08:00
2019-08-21 10:10:08 +08:00
//If last characters are same then continue
//for the rest of them.
if (str1[m - 1] == str2[n - 1])
return editDist(str1, str2, m - 1, n - 1);
//If last not same, then 3 possibilities
//a.Insert b.Remove c. Replace
//Get min of three and continue for rest.
return 1 + min(editDist(str1, str2, m, n - 1),
editDist(str1, str2, m - 1, n),
editDist(str1, str2, m - 1, n - 1));
2017-10-28 18:06:20 +08:00
}
/* A DP based program
* O(m x n)
*/
2019-08-21 10:10:08 +08:00
int editDistDP(string str1, string str2, int m, int n)
{
2017-10-28 18:06:20 +08:00
//Create Table for SubProblems
2019-08-21 10:10:08 +08:00
int dp[m + 1][n + 1];
2017-10-28 18:06:20 +08:00
//Fill d[][] in bottom up manner
2019-08-21 10:10:08 +08:00
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
2017-10-28 18:06:20 +08:00
//If str1 empty. Then add all of str2
2019-08-21 10:10:08 +08:00
if (i == 0)
2017-10-28 18:06:20 +08:00
dp[i][j] = j;
2019-08-21 10:10:08 +08:00
//If str2 empty. Then add all of str1
else if (j == 0)
2017-10-28 18:06:20 +08:00
dp[i][j] = i;
2019-08-21 10:10:08 +08:00
//If character same. Recur for remaining
else if (str1[i - 1] == str2[j - 1])
dp[i][j] = dp[i - 1][j - 1];
2017-10-28 18:06:20 +08:00
else
2019-08-21 10:10:08 +08:00
dp[i][j] = 1 + min(dp[i][j - 1], //Insert
dp[i - 1][j], //Remove
dp[i - 1][j - 1] //Replace
);
2017-10-28 18:06:20 +08:00
}
}
return dp[m][n];
}
2019-08-21 10:10:08 +08:00
int main()
{
2017-10-28 18:06:20 +08:00
string str1 = "sunday";
string str2 = "saturday";
2019-08-21 10:10:08 +08:00
cout << editDist(str1, str2, str1.length(), str2.length()) << endl;
cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl;
2017-10-28 18:06:20 +08:00
return 0;
}