Java Program for Longest Common Subsequence

JavaObject Oriented ProgrammingProgramming

Following is the Java program for Longest Common Subsequence −

Example

 Live Demo

public class Demo{
   int subseq(char[] a, char[] b, int a_len, int b_len){
      int my_arr[][] = new int[a_len + 1][b_len + 1];
      for (int i = 0; i <= a_len; i++){
         for (int j = 0; j <= b_len; j++){
            if (i == 0 || j == 0)
            my_arr[i][j] = 0;
            else if (a[i - 1] == b[j - 1])
            my_arr[i][j] = my_arr[i - 1][j - 1] + 1;
            else
            my_arr[i][j] = max_val(my_arr[i - 1][j], my_arr[i][j - 1]);
         }
      }
      return my_arr[a_len][b_len];
   }
   int max_val(int val_1, int val_2){
      return (val_1 > val_2) ? val_1 : val_2;
   }
   public static void main(String[] args){
      Demo my_inst = new Demo();
      String my_str_1 = "MNSQR";
      String my_str_2 = "PSQR";
      char[] a = my_str_1.toCharArray();
      char[] b = my_str_2.toCharArray();
      int a_len = a.length;
      int b_len = b.length;
      System.out.println("The length of the longest common subsequence is"+ " " + my_inst.subseq(a, b, a_len,       b_len));
   }
}

Output

The length of the longest common subsequence is 3

A class named Demo contains a function called "subseq" which returns the longest common subsequence for the given strings i.e str_1[0 to len(str_1-1) , str_2(0 to len(str_2-1) //2 'for' loops are iterated over the length of both the strings and if both 'i' and 'j' are 0, then, the array's specific indices are assigned to 0. Otherwise, my_arr[length of first string +1][length of second string +1] is built.

The main function defines a new instance of the Demo class and defines two strings my_str_1 and my_str_2. Both the strings are converted to arrays and their lengths are stored in separate variables. The function is called on these values.

This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array.

raja
Published on 04-Jul-2020 10:53:01
Advertisements