1
+
2
+ // A Naive recursive Java program to find minimum number
3
+ // operations to convert str1 to str2
4
+ class EDIST
5
+ {
6
+ static int min (int x ,int y ,int z )
7
+ {
8
+ if (x <=y && x <=z ) return x ;
9
+ if (y <=x && y <=z ) return y ;
10
+ else return z ;
11
+ }
12
+
13
+ static int editDist (String str1 , String str2 , int m ,int n )
14
+ {
15
+ // If first string is empty, the only option is to
16
+ // insert all characters of second string into first
17
+ if (m == 0 ) return n ;
18
+
19
+ // If second string is empty, the only option is to
20
+ // remove all characters of first string
21
+ if (n == 0 ) return m ;
22
+
23
+ // If last characters of two strings are same, nothing
24
+ // much to do. Ignore last characters and get count for
25
+ // remaining strings.
26
+ if (str1 .charAt (m -1 ) == str2 .charAt (n -1 ))
27
+ return editDist (str1 , str2 , m -1 , n -1 );
28
+
29
+ // If last characters are not same, consider all three
30
+ // operations on last character of first string, recursively
31
+ // compute minimum cost for all three operations and take
32
+ // minimum of three values.
33
+ return 1 + min ( editDist (str1 , str2 , m , n -1 ), // Insert
34
+ editDist (str1 , str2 , m -1 , n ), // Remove
35
+ editDist (str1 , str2 , m -1 , n -1 ) // Replace
36
+ );
37
+ }
38
+
39
+ public static void main (String args [])
40
+ {
41
+ String str1 = "sunday" ;
42
+ String str2 = "saturday" ;
43
+
44
+ System .out .println ( editDist ( str1 , str2 , str1 .length (), str2 .length ()) );
45
+ }
46
+ }
0 commit comments