Open In App

How to Calculate the Levenshtein Distance Between Two Strings in Java Using Recursion?

In Java, the Levenshtein Distance Algorithm is a pre-defined method used to measure the similarity between two strings and it can be used to calculate the minimum number of single-character edits (inserts, deletions, or substitutions) required to change one string into another.

Prerequisites:



How Does this Algorithm Work?

First, initialize the 2D array with the size of (m+1) * (n+1) where m and n are the lengths of the two input strings. Check the base cases if any one of the strings is empty then return the length of the other string.

if(len1 != 0 & len2 != 0)  then proceed to next steps

After that initialize the first row and column of the 2D array with values representing the number of operation edits required to transform an empty string to the corresponding prefix of the input string. Measure the distances travel through the characters of both strings.



Print the minimum cost operations results then the value represents the Levenshtein distance between the two strings.

Sample Program




// Java Program to Calculate the Levenshtein distance
// Between two Strings in Java Using Recursion
  
public class GfGLevenshteinDistance {
      
    public static int calculateDistance(String str1, String str2) {
        return calculateDistanceRecursive(str1, str1.length(), str2, str2.length());
    }
  
    private static int calculateDistanceRecursive(String str1, int len1, String str2, int len2) {
        // Base cases: if either string is empty,
          // return the length of the other string
        if (len1 == 0) {
            return len2;
        }
        if (len2 == 0) {
            return len1;
        }
  
        // If the last characters of the strings are equal,
          // No operation is required
        if (str1.charAt(len1 - 1) == str2.charAt(len2 - 1)) {
            return calculateDistanceRecursive(str1, len1 - 1, str2, len2 - 1);
        }
  
        // Calculate cost of three possible operations
          // Insertion, Deletion, and Substitution
        int insertionCost = calculateDistanceRecursive(str1, len1, str2, len2 - 1);
        int deletionCost = calculateDistanceRecursive(str1, len1 - 1, str2, len2);
        int substitutionCost = calculateDistanceRecursive(str1, len1 - 1, str2, len2 - 1);
  
        // Return minimum of the three
          // costs plus 1 (for the operation)
        return 1 + Math.min(Math.min(insertionCost, deletionCost), substitutionCost);
    }
  
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "JavaScript";
        int distance = calculateDistance(str1, str2);
        System.out.println("Levenshtein distance between \"" + str1 + "\" and \"" + str2 + "\" is: " + distance);
    }
}

Output
Levenshtein distance between "Java" and "JavaScript" is: 6






Explanation of the above Program:

In the above example, the program calculates the Levenshtein distance between two strings:


Article Tags :