vamsu
8/25/2018 - 5:06 PM

LCS

LCS

import java.io.*;
import java.util.*;


class Solution {
  public static void main(String[] args) {
    Solution solution = new Solution();
    System.out.println(solution.longestSubSequence("ABCBDAB", "BDCABA"));
    System.out.println(solution.longestSubSequenceDP("ABCBDAB", "BDCABA"));
    System.out.println(solution.longestSubSequenceDPEfficient("BDCABA","ABCBDAB"));
  }
  
  private int longestSubSequence(String s1, String s2){
    if(s1 == null || s2 == null | s1.length() < 1 || s2.length() < 1) {
      return 0;
    }
    return longestSubSequence(s1, s2, s1.length()-1, s2.length()-1);
  }
  
  private int longestSubSequence(String s1, String s2, int m, int n){
    if(m < 0 || n < 0 ) {
      return 0; 
    }
    if(s1.charAt(m) == s2.charAt(n)){
      return 1 + longestSubSequence(s1, s2, m-1, n-1);
    }
    
    return Math.max(longestSubSequence(s1, s2, m, n-1), 
                  longestSubSequence(s1, s2, m-1, n));
  }
  
  public int longestSubSequenceDP(String s1, String s2) {
    if(s1 == null || s2 == null | s1.length() < 1 || s2.length() < 1) {
      return 0;
    }
    int m = s1.length()+1;
    int n = s2.length()+1;
    int[][] tracker = new int[m][n];
    
    for(int i=1;i<m;i++) {
      for(int j=1;j<n;j++) {
        if(s1.charAt(i-1) == s2.charAt(j-1)){
          tracker[i][j] = 1+tracker[i-1][j-1]; 
        } else {
          tracker[i][j] = Math.max(tracker[i-1][j], tracker[i][j-1]); 
        }
      }
    }
    
    return tracker[m-1][n-1];
  }
  
  public int longestSubSequenceDPEfficient(String s1, String s2){
    if(s1 == null || s2 == null | s1.length() < 1 || s2.length() < 1) {
      return 0;
    }
    int m = s1.length()+1;
    int n = s2.length()+1;
    int[] tracker = new int[n];
    for(int i=1;i<m;i++) {
      for(int j=1;j<n;j++) {
        if(s1.charAt(i-1) == s2.charAt(j-1)){
          tracker[j] = 1 + tracker[j];
        } else {
          tracker[j] = Math.max(tracker[j],tracker[j-1]);
        }
        //System.out.print(s1.charAt(i-1)+"|"+s2.charAt(j-1));
      }
      // System.out.println();
      // System.out.println(Arrays.toString(tracker));
    }
    return tracker[n-1];
  }
}