# Longest Common Subsequence in C++

Suppose we have two strings text1 and text2, we have to return the length of their longest common subsequence. The ubsequence of a string is a new string generated from the original string with some characters deleted without changing the relative order of the remaining characters. (So for example "abe" is a subsequence of "abcde" but "adc" is not). A common subsequence of two strings is a subsequence that is common to both strings. So If there is no common subsequence, return 0. If the input is like “abcde”, and “ace”, then the result will be 3.

To solve this, we will follow these steps −

• n := size of s, m := size of x

• if either n is 0, or m is 0, then return 0

• s := empty string, concatenated with s

• x := empty string, concatenated with x

• ret := 0

• define a matrix dp of order (n + 1) x (m + 1)

• for i in range 1 to n

• for j in range 1 to m

• dp[i, j] := max of dp[i, j - 1] and dp[i – 1, j]

• if s[i] = x[j], then

• dp[i, j] := max of dp[i, j], 1 + dp[i – 1, j – 1]

• return dp[n, m]

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestCommonSubsequence(string s, string x) {
int n = s.size();
int m = x.size();
if(!n || !m) return 0;
s = " " + s;
x = " " + x;
int ret = 0;
vector < vector <int> > dp(n + 1, vector <int>(m + 1));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m ; j++){
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
if(s[i] == x[j]) {
dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
}
}
}
return dp[n][m];
}
};
main(){
Solution ob;
cout << (ob.longestCommonSubsequence("abcde", "ace"));
}

### Input

"abcde"
"ace"

## Output

3

Updated on: 30-Apr-2020

311 Views

##### Kickstart Your Career

Get certified by completing the course