
public class LongestCommonSubseq {


  public static String lcs( String u, String v ) {
  
    if ( (u.length() == 0) || (v.length() == 0) ) {
    
      return "";
    
    } else if ( u.charAt(0) == v.charAt(0) ) {
    
      return ( "" + u.charAt(0) + lcs( u.substring(1), v.substring(1) ) );
    
    } else {
    
      String s = lcs( u, v.substring(1) );
      String t = lcs( u.substring(1), v );
      
      if ( s.length() < t.length() ) {
        return t;
      } else {
        return s;
      }
    }
  }
  
  
  public static String longestCommonSubseq( String u, String v ) {
  
    int rows = u.length() + 1;
    int cols = v.length() + 1;
    String[][] history = new String[rows][cols];
    
    for (int i=0; i<rows; i=i+1) {
      for (int j=0; j<cols; j=j+1) {
        history[i][j] = null;
      }
    }
    return memoization_lcs( 0,0, u,v, history );
  }

  public static String memoization_lcs( int i, int j,
                         String u, String v, String[][] history ) {
  
    if ( history[i][j] == null ) {
      if ( (i == u.length()) || (j == v.length()) ) {
        history[i][j] = "";
      } else if ( u.charAt(i) == v.charAt(j) ) {
        history[i][j] =
          "" + u.charAt(i) + memoization_lcs( i+1,j+1, u,v, history );
      } else {
        String s = memoization_lcs( i,j+1, u,v, history );
        String t = memoization_lcs( i+1,j, u,v, history );
        if ( s.length() < t.length() ) {
          history[i][j] = t;
        } else {
          history[i][j] = s;
        }
      }
    }
    return history[i][j];
  }
  
  
  public static void main( String[] args ) {
  
    // System.out.println( lcs(args[0],args[1]) );
    System.out.println( longestCommonSubseq(args[0],args[1]) );
  }

}


/*

java Lcs improrogabilmente reciprocamente
iproamente
java Lcs probabilmente impertinente
priente
java Lcs reciprocamente impertinente
iprente
java Lcs impercettibilmente impredittibilmente
imprettibilmente
java Lcs ricettacolo caritatevole
rittol

*/

