Java LCS lcs(char[] A, char[] B)

Here you can find the source of lcs(char[] A, char[] B)

Description

lcs

License

Open Source License

Declaration

public static String lcs(char[] A, char[] B) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String lcs(char[] A, char[] B) {

        if (A == null || B == null)
            return null;

        final int n = A.length;
        final int m = B.length;

        if (n == 0 || m == 0)
            return null;

        int[][] dp = new int[n + 1][m + 1];

        // Suppose A = a1a2..an-1an and B = b1b2..bn-1bn 
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {

                // If ends match the LCS(a1a2..an-1an, b1b2..bn-1bn) = LCS(a1a2..an-1, b1b2..bn-1) + 1
                if (A[i - 1] == B[j - 1])
                    dp[i][j] = dp[i - 1][j - 1] + 1;

                // If the ends do not match the LCS of a1a2..an-1an and b1b2..bn-1bn is
                // max( LCS(a1a2..an-1, b1b2..bn-1bn), LCS(a1a2..an-1an, b1b2..bn-1) )
                else
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);

            }// w  w  w.jav a 2  s  .  com
        }

        int lcsLen = dp[n][m];
        char[] lcs = new char[lcsLen];
        int index = 0;

        // Backtrack to find a LCS. We search for the cells
        // where we included an element which are those with 
        // dp[i][j] != dp[i-1][j] and dp[i][j] != dp[i][j-1])
        int i = n, j = m;
        while (i >= 1 && j >= 1) {

            int v = dp[i][j];

            // The order of these may output different LCSs
            while (i > 1 && dp[i - 1][j] == v)
                i--;
            while (j > 1 && dp[i][j - 1] == v)
                j--;

            // Make sure there is a match before adding
            if (v > 0)
                lcs[lcsLen - index++ - 1] = A[i - 1]; // or B[j-1];

            i--;
            j--;

        }

        return new String(lcs, 0, lcsLen);

    }
}

Related

  1. lcs(char[] inputString1, char[] inputString2, int length1, int length2)
  2. LCS(String a, String b)
  3. lcs(String a, String b)
  4. LCS(String A, String B)