joshita / dev

Published

- 2 min read

Longest common subsequence in given strings

img of Longest common subsequence in given strings

Longest common subsequence

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, “ace” is a subsequence of “abcde”. A common subsequence of two strings is a subsequence that is common to both strings

      private int lcsWithDp(String source1, String source2, int length1, int length2, int dp[][]) {
        int result =0;
        if(dp[length1][length2]!= -1) {
            return dp[length1][length2];
        }
        if(length1 < 0 || length2 < 0) {
            return 0;
        }
        if(source1.charAt(length1) == source2.charAt(length2)) { 
            result = 1 +  lcsWithDp(source1, source2, length1-1, length2-1, dp);
        } else {
            result = Math.max(lcsWithDp(source1, source2, length1-1, length2, dp), lcsWithDp(source1, source2, length1, length2-1, dp));
        }
        return result;
       }

    private int lcsBottomUpApproach(String source1, String source2, int length1, int length2 ) {
           //100% for loop is used, same conditions just updating dp differently
           int dp[][] = new int[source1.length()+1][source2.length()+1];
           for (int i=1; i < source1.length(); i++ ) {
             for (int j=1; j < source2.length() ; j++) {
                 if(dp[i-1] == dp[j-1]) {
                    dp[i][j] += 1;
                 } else {
                    dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
                 }
             }
           }
           return dp[source1.length()][source2.length()];
       }