Java LCS lcs(String s1, String s2)

Here you can find the source of lcs(String s1, String s2)

Description

lcs

License

Open Source License

Declaration

public static String lcs(String s1, String s2) 

Method Source Code

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

public class Main {
    public static String lcs(String s1, String s2) {
        int l1 = s1.length();
        int l2 = s2.length();

        int[][] val = new int[l1 + 1][l2 + 1];
        int[][] dir = new int[l1 + 1][l2 + 1];

        for (int i = 0; i <= l2; i++) {
            val[0][i] = 0;
            dir[0][i] = 2;/*from w  ww.  j a va2  s .c o  m*/
        }

        for (int i = 0; i <= l1; i++) {
            val[i][0] = 0;
            dir[i][0] = 1;
        }

        int tVal, tDir;
        for (int i = 1; i <= l1; i++) {
            for (int j = 1; j <= l2; j++) {
                // up
                tVal = val[i - 1][j];
                tDir = 1;

                // left
                if (val[i][j - 1] > tVal) {
                    tVal = val[i][j - 1];
                    tDir = 2;
                }

                // diagonal
                if (s1.charAt(i - 1) == s2.charAt(j - 1) && val[i - 1][j - 1] + 1 > tVal) {
                    tVal = val[i - 1][j - 1] + 1;
                    tDir = 3;
                }

                val[i][j] = tVal;
                dir[i][j] = tDir;
            }
        }

        return getSolution(dir, s1, s2);
    }

    private static String getSolution(int[][] dir, String s1, String s2) {
        StringBuilder sb = new StringBuilder();
        int i = s1.length(), j = s2.length();
        int tDir;
        while (i > 0 && j > 0) {
            tDir = dir[i][j];
            switch (tDir) {
            case 1:
                i--;
                break;
            case 2:
                j--;
                break;
            case 3:
                i--;
                j--;
                sb.append(s1.charAt(i));
                break;
            }
        }

        return sb.reverse().toString();
    }
}

Related

  1. LCS(String A, String B)
  2. lcs(String a, String b)
  3. lcs(String arg0, String arg1)
  4. LCS(String input1, String input2)
  5. lcs(String s1, int s1min, int s1max, String s2, int s2min, int s2max)
  6. lcs(String str1, String str2)
  7. lcs(String X, String Y, int m, int n)
  8. lcs1(int[] A, int[] B)
  9. lcs2(int[] A, int[] B, int m, int n)