- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

#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

- Related Questions & Answers
- Longest Common Subsequence
- C++ Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
- Program to find length of longest common subsequence in C++
- Longest Bitonic Subsequence
- Longest Increasing Subsequence
- Longest Palindromic Subsequence
- Program to find length of longest common subsequence of three strings in Python
- Longest Increasing Subsequence in Python
- Longest Palindromic Subsequence in C++
- Longest Harmonious Subsequence in C++
- Longest Uncommon Subsequence I in C++
- Longest Continuous Increasing Subsequence in C++
- Longest Uncommon Subsequence II in C++
- Longest decreasing subsequence subarray in JavaScript