Skip to content

Commit

Permalink
Merge pull request shivaylamba#709 from geekaditi/master
Browse files Browse the repository at this point in the history
Create Longest-Common-Subsequence
  • Loading branch information
shivaylamba authored Oct 10, 2020
2 parents 75b046a + 156a0b4 commit 1849b00
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions Languages/C++/Longest-Common-Subsequence
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/* Longest Common Subsequence problem solved in CPP using Dynamic Programming */

#include <iostream>
#include <vector>
using namespace std;

int LCS(char *a,char *b){
int n = strlen(a);
int m = strlen(b);

int dp[100][100] = {0};
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(a[i-1] == b[j-1]){
dp[i][j] = 1 + dp[i-1][j-1];
}
else{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}

for(int i=0;i<=n;i++){
for(int j=0;j<=m;j++){
cout<<dp[i][j]<<' ';
}
cout<<endl;
}

int k = dp[n][m];
char ans[100];
ans[k] = '\0';
k--;
int i = n;
int j = m;

while(k>=0){
if(a[i-1] == b[j-1]){
ans[k] = a[i-1];
k--;i--;j--;
}
else{
if(dp[i-1][j]>dp[i][j-1]){
i--;
}
else{
j--;
}
}
}
cout<<"LCS is "<<ans<<endl;
return dp[n][m];
}

int main(){

char a[]="coddingblockss";
char b[]="codppqwertblocks";

cout<<LCS(a,b)<<endl;



return 0;
}

0 comments on commit 1849b00

Please sign in to comment.