-
Notifications
You must be signed in to change notification settings - Fork 117
/
DP - 2:Edit Distance(Memoization and DP)
80 lines (74 loc) · 2.37 KB
/
DP - 2:Edit Distance(Memoization and DP)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//memoization//
// public class Solution {
// public static int editDistance(String s1, String s2){
// int m=s1.length();
// int n=s2.length();
// int storage [][]=new int [m+1][n+1];
// for(int i=0;i<=m;i++){
// for(int j=0;j<=n;j++){
// storage[i][j]=-1;
// }
// }
// return editDistance(s1,s2,storage);
// }
// private static int editDistance(String s1,String s2,int storage[][]){
// int m=s1.length();
// int n=s2.length();
// if(m==0 && n==0){
// storage[m][n]=0;
// return storage[m][n];}
// if(m==0){
// storage[m][n]=n;
// return storage[m][n];}
// if(n==0){
// storage[m][n]=m;
// return storage[m][n];}
// if(storage[m][n]!=-1)
// return storage[m][n];
// else{
// if(s1.charAt(0)==s2.charAt(0))
// return editDistance(s1.substring(1),s2.substring(1),storage);
// else{
// //insert
// int op1=editDistance(s1,s2.substring(1),storage);
// //delete
// int op2=editDistance(s1.substring(1),s2,storage);
// //sustitute
// int op3=editDistance(s1.substring(1),s2.substring(1),storage);
// storage[m][n]=1+Math.min(op1,Math.min(op2,op3));
// }
// }
// return storage[m][n];
// }
// }
//Dp/////////////////////////////////////////////////////////////////
public class Solution {
public static int editDistance(String s1, String s2){
int m=s1.length();
int n=s2.length();
if(m==0 && n==0)
return 0;
if(m==0)
return n;
if(n==0)
return m;
int storage[][]=new int[m+1][n+1];
storage[0][0]=0;
for(int i=1;i<=n;i++)
storage[0][i]=i;
for(int i=1;i<=m;i++)
storage[i][0]=i;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(s1.charAt(m-i)==s2.charAt(n-j))
{
storage[i][j]=storage[i-1][j-1];
}
else{
storage[i][j]=1+Math.min(Math.min(storage[i-1][j],storage[i][j-1]),storage[i-1][j-1]);
}
}
}
return storage[m][n];
}
}