implement Longest Common Subsequence Algorithm - Java Algorithm

Java examples for Algorithm:String

Description

implement Longest Common Subsequence Algorithm

Test cases

You can use the following test cases to verify your code logics.

ID Input Ouput
1abcf abcd abc
2aaa a a
3aa aa aa

Code template

Cut and paste the following code snippet to start solve this problem.

import java.io.IOException;

public class Main{
  public static void main(String[] args) throws IOException {
    System.out.println("Longest Common Subsequence : " + lcs("abcf", "abcd"));
  }
  public static String lcs(String str1, String str2) {
     //your code
  }

}

Answer

Here is the answer to the question above.

Demo Code


import java.io.IOException;

public class Main{
  public static void main(String[] args) throws IOException {
    System.out.println("Longest Common Subsequence : " + lcs("abcf", "abcd"));
  }//from  w  w  w  .  j a v  a2 s . c om
  public static String lcs(String str1, String str2) {
    int l1 = str1.length();
    int l2 = str2.length();

    int[][] arr = new int[l1 + 1][l2 + 1];

    for (int i = l1 - 1; i >= 0; i--) {
      for (int j = l2 - 1; j >= 0; j--) {
        if (str1.charAt(i) == str2.charAt(j))
          arr[i][j] = arr[i + 1][j + 1] + 1;
        else
          arr[i][j] = Math.max(arr[i + 1][j], arr[i][j + 1]);
       // System.out.println(" " + arr[i][j]);
      }
    }

    int i = 0, j = 0;
    StringBuffer sb = new StringBuffer();
    while (i < l1 && j < l2) {
      if (str1.charAt(i) == str2.charAt(j)) {
        sb.append(str1.charAt(i));
        i++;
        j++;
      } else if (arr[i + 1][j] >= arr[i][j + 1])
        i++;
      else
        j++;
    }
    return sb.toString();
  }

}

Related Tutorials