TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
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>
17
using namespace
std;
18
19
int
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
*/
26
int
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
*/
48
int
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
78
int
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
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
endl
#define endl
Definition
matrix_exponentiation.cpp:36
dp
for std::vector
Definition
partition_problem.cpp:39
dynamic_programming
edit_distance.cpp
Generated by
1.18.0