Skip to content

Commit fada4e5

Browse files
authored
Create Dameray-Levenshtein.java
1 parent 2a518e3 commit fada4e5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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

0 commit comments

Comments
 (0)