Java LCS LCS(String A, String B)

Here you can find the source of LCS(String A, String B)

Description

LCS

License

Apache License

Declaration

public static int LCS(String A, String B) 

Method Source Code

//package com.java2s;
/**//from   w  w  w . j  a va2s  .co m
 * Copyright 2015-2016 Debmalya Jash
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    public static int LCS(String A, String B) {
        if (A.length() == 0 || B.length() == 0) {
            return 0;
        }
        int lenA = A.length();
        int lenB = B.length();
        // check if last characters are same
        if (A.charAt(lenA - 1) == B.charAt(lenB - 1)) {
            // Add 1 to the result and remove the last character from both
            // the strings and make recursive call to the modified strings.
            return 1 + LCS(A.substring(0, lenA - 1), B.substring(0, lenB - 1));
        } else {
            // Remove the last character of String 1 and make a recursive
            // call and remove the last character from String 2 and make a
            // recursive and then return the max from returns of both recursive
            // calls
            return Math.max(LCS(A.substring(0, lenA - 1), B.substring(0, lenB)),
                    LCS(A.substring(0, lenA), B.substring(0, lenB - 1)));
        }
    }
}

Related

  1. lcs(char[] A, char[] B)
  2. lcs(char[] inputString1, char[] inputString2, int length1, int length2)
  3. LCS(String a, String b)
  4. lcs(String a, String b)
  5. lcs(String a, String b)
  6. lcs(String arg0, String arg1)
  7. LCS(String input1, String input2)