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 c505e96

Browse files
Create Edit Distance
1 parent 75bedd7 commit c505e96

File tree

1 file changed

+76
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 19 - Dynamic Programming II

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
You are given two strings S and T of lengths M and N, respectively. Find the 'Edit Distance' between the strings.
3+
Edit Distance of two strings is the minimum number of steps required to make one string equal to the other. In order to do so, you can perform the following three operations:
4+
1. Delete a character
5+
2. Replace a character with another one
6+
3. Insert a character
7+
Note : Strings don't contain spaces in between.
8+
9+
Input format :
10+
The first line of input contains the string S of length M.
11+
The second line of the input contains the String T of length N.
12+
13+
Output format :
14+
Print the minimum 'Edit Distance' between the strings.
15+
16+
Constraints :
17+
0 <= M <= 10 ^ 3
18+
0 <= N <= 10 ^ 3
19+
Time Limit: 1 sec
20+
21+
Sample Input 1 :
22+
abc
23+
dc
24+
Sample Output 1 :
25+
2
26+
Explanation to the Sample Input 1 :
27+
In 2 operations we can make string T to look like string S.
28+
First, insert character 'a' to string T, which makes it "adc".
29+
And secondly, replace the character 'd' of string T with 'b' from the string S. This would make string T as "abc" which is also string S.
30+
Hence, the minimum distance.
31+
32+
Sample Input 2 :
33+
whgtdwhgtdg
34+
aswcfg
35+
Sample Output 2 :
36+
9
37+
*/
38+
39+
public class Solution {
40+
41+
public static int editDistance(String s, String t) {
42+
//Your code goes here
43+
//Find the lengths of both strings
44+
int m=s.length();
45+
int n=t.length();
46+
47+
int[][] dp = new int[m+1][n+1];
48+
//Initializing dp for iterative approach
49+
for (int i=n;i>=0;i--)
50+
dp[m][i]=n-i;
51+
52+
for (int i=m;i>=0;i--)
53+
dp[i][n]=m-i;
54+
55+
for (int i=m-1;i>=0;i--)
56+
{
57+
for (int j=n-1;j>=0;j--)
58+
{
59+
if (s.charAt(i)==t.charAt(j))
60+
{
61+
dp[i][j]=dp[i+1][j+1];
62+
}
63+
else
64+
{
65+
int ans1=1+dp[i+1][j+1];
66+
int ans2=1+dp[i][j+1];
67+
int ans3=1+dp[i+1][j];
68+
69+
dp[i][j]=Math.min(ans1,Math.min(ans2,ans3));
70+
}
71+
}
72+
}
73+
return dp[0][0];
74+
}
75+
76+
}

0 commit comments

Comments
(0)

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