Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 14, 2017 00:37
Show Gist options
  • Save sdpatil/f4079287e5b03adfcafe623eade45979 to your computer and use it in GitHub Desktop.
Save sdpatil/f4079287e5b03adfcafe623eade45979 to your computer and use it in GitHub Desktop.
Compute the Levenshtein distance
import java.util.Arrays;
/**
* Problem: Write a program that takes two strings and computes the minimum number of edits needed to transform the
* first string into the second string
*/
public class LevenshteinDistance {
/*
First create 2 dimensional array with int[A.length()+1][B.length()+1].
Then initialize all the values in 0th row equal to column count and same with 0th column
*/
public int levenshteinDistanceDP(String A, String B) {
int[][] dpTable = new int[A.length()+1][B.length()+1];
dpTable[0][0] = 0;
//Initialize first column
for(int i = 0; i < dpTable.length ; i++)
dpTable[i][0] = i;
//Initialize first row
for(int i = 0 ; i < dpTable[0].length ; i++)
dpTable[0][i] = i;
//Now start compairing letters, if A.charAt(i-1) == B.charAt(j-1) is same copy count from diagonally opposite
// value, if not its the min of top, left and diagonal +1
for(int i = 1 ; i <= A.length() ; i++){
for(int j = 1 ; j <= B.length() ; j++){
if(A.charAt(i-1) == B.charAt(j-1)){
dpTable[i][j] = dpTable[i-1][j-1];
}else{
dpTable[i][j] = Math.min(dpTable[i-1][j-1], Math.min(dpTable[i-1][j],dpTable[i][j-1])) +1;
}
}
}
for(int[] dpRow: dpTable)
System.out.println(Arrays.toString(dpRow));
return dpTable[A.length()][B.length()];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment