logo CodeStepByStep logo

longestCommonSubsequence

Language/Type: C++ dynamic programming

Write a function 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, vector, set, map, etc.) necessary to store the data for your dynamic programming algorithm. You are also allowed to define other "helper" functions if you like.

Type your C++ solution code here:


This is a function exercise. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

Need help?

If you do not understand how to solve an exercise or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect tests, etc.), please

Is there a problem? Contact a site administrator.

©, all rights reserved.