Java examples for Algorithm:String
implement Longest Common Subsequence Algorithm
You can use the following test cases to verify your code logics.
ID | Input | Ouput |
---|---|---|
1 | abcf abcd | abc |
2 | aaa a | a |
3 | aa aa | aa |
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 } }
Here is the answer to the question above.
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(); } }