Here you can find the source of getLongestCommonSubsequence(int[] a, int[] b)
Parameter | Description |
---|---|
a | first integer array. |
b | second integer array. |
public static String getLongestCommonSubsequence(int[] a, int[] b)
//package com.java2s; /**/*w w w . j a v a 2 s . c o m*/ * Copyright 2015-2016 Debmalya Jash * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Arrays; public class Main { /** * @param a * first integer array. * @param b * second integer array. * @return string containing longest common subsequence. */ public static String getLongestCommonSubsequence(int[] a, int[] b) { String result = ""; int[][] LCS = new int[a.length + 1][b.length + 1]; String[][] solution = new String[a.length + 1][b.length + 1]; // if A is null then LCS of A, B =0 for (int i = 0; i <= b.length; i++) { LCS[0][i] = 0; solution[0][i] = "0"; } // if B is null then LCS of A, B =0 for (int i = 0; i <= a.length; i++) { LCS[i][0] = 0; solution[i][0] = "0"; } for (int i = 1; i <= a.length; i++) { for (int j = 1; j <= b.length; j++) { if (a[i - 1] == b[i - 1] && a[i - 1] != 0) { solution[i][j] = "" + a[i - 1]; } } } for (int i = 0; i < solution.length; i++) { System.out.println(Arrays.toString(solution[i])); } return result.trim(); } /** * @param a * first integer array. * @param b * second integer array. * @return string containing longest common subsequence. */ public static String getLongestCommonSubsequence(char[] a, char[] b) { StringBuilder answer = new StringBuilder(); // First Property // Suppose that two sequences both end in the same element. To find // their LCS, shorten each sequence by removing the last element, find // the LCS of the shortened sequences, and to that LCS append the // removed element. int ae = a.length - 1; int be = b.length - 1; while (a[ae--] == b[be--]) { // both end with the same element. answer.append(a[ae + 1]); } if (answer.length() > 0) { answer = answer.reverse(); } StringBuilder prefix = new StringBuilder(); for (int i = ae; i > -1; i--) { for (int j = be; j > -1; j--) { if (a[i] == b[j]) { prefix.append(a[i]); } } } if (prefix.length() > 0) { prefix = prefix.reverse(); prefix.append(answer); answer = prefix; } return answer.toString(); } }