logo CodeStepByStep logo

longestCommonSubsequence

Language/Type: Java recursion recursive backtracking
Related Links:

Write a recursive method longestCommonSubsequence that accepts two strings as parameters and uses recursive backtracking to determine and return the longest common subsequence of characters that appear in both strings. A common subsequence is defined as a sequence of characters that appear in both strings in the same relative order. For example, given the two strings "ABCDEFG" and "BGCEHAF", the longest subsequence between them is "BCEF" because those characters "B", "C", "E", and "F" appear in both strings in the same relative order. The characters in the subsequence need not occur consecutively, and they do not have to occur at the same indexes within the two strings.

If the two strings have no characters in common, or if either string is an empty string, "" should be returned.

Here are some calls to your method and their expected return values.

Call Value Returned
longestCommonSubsequence("ABCDEFG", "BGCEHAF") "BCEF"
longestCommonSubsequence("she sells", "seashells") "sesells"
longestCommonSubsequence("12345", "54321 21 54321") "123"
longestCommonSubsequence("supercilious teacher", "delicious peach") "ecious each"
longestCommonSubsequence("Marty", "Helene") ""
longestCommonSubsequence("", "Joe") ""
longestCommonSubsequence("Suzy", "") ""
longestCommonSubsequence("ACGGTGTCGTGCTTA", "CGTTCGGCTATCGTACGTT") "CGGTTCGTGTTA"

Looking for common subsequences is an important algorithm in computer science, from analyzing genetic data (looking for common DNA or proteins) to comparing text files for similarities and differences (as done by our course web site's Output Comparison Tool and the Unix diff command).

Do not use any loops in solving this problem.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.