Here you can find the source of lcs(String s1, String s2)
public static String lcs(String s1, String s2)
//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(); } }