DEV Community

Sayani Mallick
Sayani Mallick

Posted on

Longest common subsequence in C++

The longest common subsequence is a standard dynamic programming problem. In the longest common subsequence problem, two strings are given. The aim is to find out the length of the longest common subsequence.
Example:
INPUT:
abcde
abxyzd

OUTPUT:3

The output of the above input will be 3 because the longest common subsequence is abd.

Other examples:
INPUT:
axyz
ghjk
OUTPUT:0
There is no common subsequence at all.

INPUT:
a
abcdefghijklmno
OUTPUT:1
The longest common subsequence is a

Using the dynamic programming concept, we form a two dimensional array
t[length_of_first_string+1][length_of_second_string+1].
We then initialize the two dimensional array as:If the length of the first string or second string is zero, then the common subsequence length will also be zero.

CODE:

Alt Text

Hope this helps you! Do follow me on Github!

Top comments (0)