logo CodeStepByStep logo

longestCommonSubsequence

Language/Type: Java dynamic programming

Write a method named longestCommonSubsequence that returns the longest common subsequence of two strings using dynamic programming. Recall that if a string is a subsequence of another, each of its letters occurs in the longer string in the same order, but not necessarily consecutively. For example, the following calls should return the following values:

Call Longest Returns
longestCommonSubsequence("marty", "megan") "ma" 2
longestCommonSubsequence("hannah", "banana") "anna" 4
longestCommonSubsequence("she sells", "seashells") "sesells" 7
longestCommonSubsequence("janet", "cs106b") "" 0

The key constraint of this problem is that you must solve it using a bottom-up dynamic programming approach. Do not use recursion. Your solution must use dynamic programming instead.

You are allowed to construct any data structures (array, list, set, map, etc.) necessary to store the data for your dynamic programming algorithm. You are also allowed to define other "helper" methods if you like.

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.