Skip to content

Commit 0843ded

Browse files
Merge pull request matthewsamuel95#70 from Bing18/new-branch
Added lcs in cpp
2 parents 99b60ff + 24a0d29 commit 0843ded

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

DP/LongestCommonSubsequence/LCS.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
#include <iostream>
3+
#include <string>
4+
#include <algorithm>
5+
using namespace std;
6+
7+
int lcs(string a,string b){
8+
int l1=a.size();
9+
int l2=b.size();
10+
//2d array for bottom-up dp
11+
int dp[l1+1][l2+1];
12+
13+
for(int i=0;i<=l1;i++){
14+
for(int j=0;j<=l2;j++){
15+
if(!i || !j)
16+
dp[i][j]=0;
17+
else if(a[i-1] == b[j-1]){
18+
dp[i][j] = dp[i-1][j-1] + 1;
19+
}
20+
else{
21+
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
22+
}
23+
}
24+
}
25+
return dp[l1][l2];
26+
}
27+
int main() {
28+
string a,b;
29+
cin>>a>>b;
30+
cout<<lcs(a,b)<<endl;
31+
return 0;
32+
}

0 commit comments

Comments
 (0)