Fix ArrayIndexOutOfBoundsException in LevenshteinDistance (#3871)

This commit is contained in:
Davide Nigri 2023-02-15 21:34:36 +01:00 committed by GitHub
parent 69a428470c
commit e0b1235bef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 26 deletions

View File

@ -17,43 +17,40 @@ public class LevenshteinDistance {
} }
} }
private static int calculate_distance(String a, String b) { public static int calculateLevenshteinDistance(String str1, String str2) {
int len_a = a.length() + 1; int len1 = str1.length() + 1;
int len_b = b.length() + 1; int len2 = str2.length() + 1;
int[][] distance_mat = new int[len_a][len_b]; int[][] distanceMat = new int[len1][len2];
for (int i = 0; i < len_a; i++) { for (int i = 0; i < len1; i++) {
distance_mat[i][0] = i; distanceMat[i][0] = i;
} }
for (int j = 0; j < len_b; j++) { for (int j = 0; j < len2; j++) {
distance_mat[0][j] = j; distanceMat[0][j] = j;
} }
for (int i = 0; i < len_a; i++) { for (int i = 1; i < len1; i++) {
for (int j = 0; j < len_b; j++) { for (int j = 1; j < len2; j++) {
int cost; if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
if (a.charAt(i) == b.charAt(j)) { distanceMat[i][j] = distanceMat[i - 1][j - 1];
cost = 0;
} else { } else {
cost = 1; distanceMat[i][j] =
} 1 + minimum(
distance_mat[i][j] = distanceMat[i - 1][j],
minimum( distanceMat[i - 1][j - 1],
distance_mat[i - 1][j], distanceMat[i][j - 1]
distance_mat[i - 1][j - 1], );
distance_mat[i][j - 1]
) +
cost;
} }
} }
return distance_mat[len_a - 1][len_b - 1]; }
return distanceMat[len1 - 1][len2 - 1];
} }
public static void main(String[] args) { public static void main(String[] args) {
String a = ""; // enter your string here String str1 = ""; // enter your string here
String b = ""; // enter your string here String str2 = ""; // enter your string here
System.out.print( System.out.print(
"Levenshtein distance between " + a + " and " + b + " is: " "Levenshtein distance between " + str1 + " and " + str2 + " is: "
); );
System.out.println(calculate_distance(a, b)); System.out.println(calculateLevenshteinDistance(str1, str2));
} }
} }

View File

@ -0,0 +1,17 @@
package com.thealgorithms.dynamicprogramming;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LevenshteinDistanceTests {
@ParameterizedTest
@CsvSource({"dog,cat,3", "sunday,saturday,3", "cat,cats,1", "rain,train,1"})
void levenshteinDistanceTest(String str1, String str2, int distance) {
int result = LevenshteinDistance.calculateLevenshteinDistance(str1, str2);
assertEquals(distance, result);
}
}