TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
edit_distance.cpp
1/* Given two strings str1 & str2
2 * and below operations that can
3 * be performed on str1. Find
4 * minimum number of edits
5 * (operations) required to convert
6 * 'str1' into 'str2'/
7 * a. Insert
8 * b. Remove
9 * c. Replace
10 * All of the above operations are
11 * of equal cost
12 */
13
14#include <iostream>
15#include <string>
16#include <vector>
17using namespace std;
18
19int min(int x, int y, int z) { return min(min(x, y), z); }
20
21/* A Naive recursive C++ program to find
22 * minimum number of operations to convert
23 * str1 to str2.
24 * O(3^m)
25 */
26int editDist(string str1, string str2, int m, int n) {
27 if (m == 0)
28 return n;
29 if (n == 0)
30 return m;
31
32 // If last characters are same then continue
33 // for the rest of them.
34 if (str1[m - 1] == str2[n - 1])
35 return editDist(str1, str2, m - 1, n - 1);
36
37 // If last not same, then 3 possibilities
38 // a.Insert b.Remove c. Replace
39 // Get min of three and continue for rest.
40 return 1 + min(editDist(str1, str2, m, n - 1),
41 editDist(str1, str2, m - 1, n),
42 editDist(str1, str2, m - 1, n - 1));
43}
44
45/* A DP based program
46 * O(m x n)
47 */
48int editDistDP(string str1, string str2, int m, int n) {
49 // Create Table for SubProblems
50 std::vector<std::vector<int> > dp(m + 1, std::vector<int>(n + 1));
51
52 // Fill d[][] in bottom up manner
53 for (int i = 0; i <= m; i++) {
54 for (int j = 0; j <= n; j++) {
55 // If str1 empty. Then add all of str2
56 if (i == 0)
57 dp[i][j] = j;
58
59 // If str2 empty. Then add all of str1
60 else if (j == 0)
61 dp[i][j] = i;
62
63 // If character same. Recur for remaining
64 else if (str1[i - 1] == str2[j - 1])
65 dp[i][j] = dp[i - 1][j - 1];
66
67 else
68 dp[i][j] = 1 + min(dp[i][j - 1], // Insert
69 dp[i - 1][j], // Remove
70 dp[i - 1][j - 1] // Replace
71 );
72 }
73 }
74
75 return dp[m][n];
76}
77
78int main() {
79 string str1 = "sunday";
80 string str2 = "saturday";
81
82 cout << editDist(str1, str2, str1.length(), str2.length()) << endl;
83 cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl;
84
85 return 0;
86}
int main()
Main function.
#define endl
for std::vector