Skip to content

Commit 752aaec

Browse files
committed
added edit distance example (dp)
1 parent e781eb5 commit 752aaec

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

Dynamic_Programming.java

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,45 @@ public static void main(String[] args) throws Exception {
3131

3232
void solve() throws Exception {
3333
//longest_increasing_subsequence();
34-
longest_common_subsequence();
34+
//longest_common_subsequence();
35+
edit_distance();
36+
}
37+
38+
void edit_distance(){
39+
String str1 = "unday";
40+
String str2 = "monday";
41+
42+
pout.println(edit_distance_dp(str1,str2));
43+
}
44+
45+
long edit_distance_dp(String s1,String s2){
46+
int len1 = s1.length();
47+
int len2 = s2.length();
48+
49+
long dp[][] = new long[len1+1][len2+1];
50+
51+
for(int i=0;i<=len1;i++){
52+
for(int j=0;j<=len2;j++){
53+
if(i==0){
54+
dp[i][j] = j;
55+
continue;
56+
}
57+
58+
if(j==0){
59+
dp[i][j] = i;
60+
continue;
61+
}
62+
63+
if(s1.charAt(i-1)==s2.charAt(j-1)){
64+
dp[i][j] = dp[i-1][j-1];
65+
}
66+
else{
67+
dp[i][j] = 1 + Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]);
68+
}
69+
}
70+
}
71+
72+
return dp[len1][len2];
3573
}
3674

3775
private void longest_common_subsequence() {

0 commit comments

Comments
 (0)