File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
src/main/java/com/thealgorithms/dynamicprogramming Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Java code to calculate optimal string alignment distance
2
+ public class Main {
3
+ public static int optimalStringAlignmentDistance (String s1 , String s2 ) {
4
+ // Create a table to store the results of subproblems
5
+ int [][] dp = new int [s1 .length ()+1 ][s2 .length ()+1 ];
6
+
7
+ // Initialize the table
8
+ for (int i = 0 ; i <= s1 .length (); i ++) {
9
+ dp [i ][0 ] = i ;
10
+ }
11
+ for (int j = 0 ; j <= s2 .length (); j ++) {
12
+ dp [0 ][j ] = j ;
13
+ }
14
+
15
+ // Populate the table using dynamic programming
16
+ for (int i = 1 ; i <= s1 .length (); i ++) {
17
+ for (int j = 1 ; j <= s2 .length (); j ++) {
18
+ if (s1 .charAt (i -1 ) == s2 .charAt (j -1 )) {
19
+ dp [i ][j ] = dp [i -1 ][j -1 ];
20
+ } else {
21
+ dp [i ][j ] = 1 + Math .min (Math .min (dp [i -1 ][j ], dp [i ][j -1 ]), dp [i -1 ][j -1 ]);
22
+ }
23
+ }
24
+ }
25
+
26
+ // Return the edit distance
27
+ return dp [s1 .length ()][s2 .length ()];
28
+ }
29
+
30
+ public static void main (String [] args ) {
31
+ System .out .println (optimalStringAlignmentDistance ("geeks" , "forgeeks" ));
32
+ }
33
+ }
34
+
35
+ //This code is contributed by shivamsharma215
You can’t perform that action at this time.
0 commit comments