public static int longestCommonSubsequence(char[] s1, char[] s2){

        int[][] length = new int[s1.length][s2.length];


        for(int i=0;i<s1.length; i++){
            for( int j=0; j< s2.length; j++) {
                // if the characters match
                 if(s1[i] == s2[j]){
                     // increase the length by 1 since i-1 and j-1 substrings
                     length[i][j] = 1+ (i-1>=0 && j-1>=0 ? length[i-1][j-1]: 0);

                 } else {
                     //otherwise find maximum of matching length by adding the last character on both the sides
                     length[i][j] = Math.max(j-1>=0?length[i][j-1]:0, i-1>=0?length[i-1][j]:0);
                 }

            }
        }

       return length[s1.length-1][s2.length-1];
    }