Java LCS lcs4(int[] A, int[] B)

Here you can find the source of lcs4(int[] A, int[] B)

Description

lcs

License

Apache License

Declaration

public static int lcs4(int[] A, int[] B) 

Method Source Code

//package com.java2s;
/*// www  .  j av  a2s  . c  o  m
 * org.fsola
 *
 * File Name: LongestCommonSubsequence.java
 *
 * Copyright 2014 Dzhem Riza
 *
 * 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
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */

public class Main {
    public static int lcs4(int[] A, int[] B) {
        int[][] M = new int[A.length + 1][B.length + 1];

        for (int i = 0; i < A.length; ++i) {
            M[i][0] = 0;
        }
        for (int j = 0; j < B.length; ++j) {
            M[0][j] = 0;
        }

        for (int i = 1; i <= A.length; ++i) {
            for (int j = 1; j <= B.length; ++j) {
                if (A[i - 1] == B[j - 1]) {
                    M[i][j] = M[i - 1][j - 1] + 1;
                } else {
                    M[i][j] = Math.max(M[i - 1][j], M[i][j - 1]);
                }
            }
        }

        System.out.println();
        System.out.print("Traceback:");
        traceBackLcs4(M, A, B, A.length, B.length);
        System.out.println();

        return M[A.length][B.length];
    }

    private static void traceBackLcs4(int[][] M, int[] A, int[] B, int i, int j) {
        if (i == 0 || j == 0) {
            return;
        } else if (A[i - 1] == B[j - 1]) {
            System.out.print(" " + A[i - 1]);
            traceBackLcs4(M, A, B, i - 1, j - 1);
        } else {
            if (M[i][j - 1] > M[i - 1][j]) {
                traceBackLcs4(M, A, B, i, j - 1);
            } else {
                traceBackLcs4(M, A, B, i - 1, j);
            }
        }
    }
}

Related

  1. lcs(String str1, String str2)
  2. lcs(String X, String Y, int m, int n)
  3. lcs1(int[] A, int[] B)
  4. lcs2(int[] A, int[] B, int m, int n)
  5. lcs3(int[] A, int[] B)
  6. LCSAlgorithm(String a, String b)
  7. lcse(String str1, String str2)
  8. LCSIterative(Character[] X, int i, Character Y[], int j, int c[][])
  9. LCSRecursive(Character[] X, int i, Character Y[], int j, int c[][])