Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 296536a

Browse files
Edit Distance
1 parent 66bb82b commit 296536a

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/* Amit Bansal - @amitbansal7 */
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
/*
6+
Edit Distance. Given two text strings A of length n and B of length m, you want to transform A into B
7+
with a minimum number of operations of the following types: delete a character from A, insert a
8+
character into A, or change some character in A into a new character. The minimal number of such
9+
operations required to transform A into B is called the edit distance between A and B.
10+
*/
11+
12+
int main()
13+
{
14+
string a = "FOOD";
15+
string b = "MONEY";
16+
17+
int al = a.length();
18+
int bl = b.length();
19+
20+
int DP[al + 1][bl + 1];
21+
22+
for (int i = 0; i <= al; i++)
23+
{
24+
for (int j = 0; j <= bl; j++)
25+
{
26+
if (i == 0)
27+
DP[i][j] = j;
28+
29+
else if (j == 0)
30+
DP[i][j] = i;
31+
32+
else if (a[i - 1] == b[j - 1])
33+
DP[i][j] = DP[i - 1][j - 1];
34+
35+
else
36+
DP[i][j] = 1 + min(DP[i - 1][j - 1], min(DP[i - 1][j], DP[i][j - 1]));
37+
}
38+
}
39+
40+
printf("%d\n",DP[al][bl]);
41+
42+
43+
return 0;
44+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/* Amit Bansal - @amitbansal7 */
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
/*
6+
Edit Distance. Given two text strings A of length n and B of length m, you want to transform A into B
7+
with a minimum number of operations of the following types: delete a character from A, insert a
8+
character into A, or change some character in A into a new character. The minimal number of such
9+
operations required to transform A into B is called the edit distance between A and B.
10+
*/
11+
12+
int DP[20][20];
13+
14+
int solve(string a, string b, int i, int j)
15+
{
16+
if (i < 1)
17+
return DP[i][j] = j;
18+
19+
else if (j < 1)
20+
return DP[i][j] = i;
21+
22+
else if (a[i-1] == b[j-1])
23+
return DP[i][j] = solve(a, b, i - 1, j - 1);
24+
25+
return DP[i][j] = 1 + min(solve(a, b, i - 1, j - 1),
26+
min(solve(a, b, i - 1, j), solve(a, b, i, j - 1)));
27+
}
28+
int main()
29+
{
30+
string a = "FOOD";
31+
string b = "MONEY";
32+
33+
int al = a.length();
34+
int bl = b.length();
35+
36+
printf("%d\n", solve(a, b, al, bl));
37+
38+
return 0;
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /