Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MuhammadJahidHasan/efab040b8ac519e75cf31459963f128d to your computer and use it in GitHub Desktop.
Save MuhammadJahidHasan/efab040b8ac519e75cf31459963f128d to your computer and use it in GitHub Desktop.
Longest common sub sequences(LCS)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string r,s1,s2;int ls1,ls2,co=0;
cin>>s1;
cin>>s2;
ls1=s1.length();
ls2=s2.length();
int arr[ls1+1][ls2+1];
for(int i=0;i<=ls1;i++){
for(int j=0;j<=ls2;j++){
if (i == 0 || j == 0)
arr[i][j] = 0;
else if(s1[i-1]==s2[j-1]){
arr[i][j]=arr[i-1][j-1]+1;
}
else
arr[i][j]=max(arr[i-1][j],arr[i][j-1]);
}
}
cout<<arr[ls1][ls2]<<endl;
int p=ls1,q=ls2;
while(p>0&&q>0){
if(s1[p-1]==s2[q-1]){
r[co]=s1[p-1];
co++;
p--;q--;
}
else if(arr[p-1][q]>arr[p][q-1])
p--;
else
q--;
}
for(int m=co-1;m>=0;m--)
cout<<r[m];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment