forked from BabesGotByte/Coding_SkillSet_Topicwise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnswer21.cpp
More file actions
33 lines (32 loc) · 751 Bytes
/
Answer21.cpp
File metadata and controls
33 lines (32 loc) · 751 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <bits/stdc++.h>
using namespace std;
//Longest Common Subsequence
//TC O(n*m)
//Dynamic Programming Memoisation
int longestCommonSubsequence(string text1, string text2)
{
int n = text1.size(), m = text2.size();
int t[n + 1][m + 1];
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= m; j++)
{
if (i == 0 || j == 0)
t[i][j] = 0; //if size is 0, lcs=0
else if (text1[i - 1] == text2[j - 1])
t[i][j] = 1 + t[i - 1][j - 1]; //take common element
else
t[i][j] = max(t[i - 1][j], t[i][j - 1]); //either of one string reduces
}
}
return t[n][m];
}
int main()
{
string a, b;
cin >> a >> b;
int ans;
ans = longestCommonSubsequence(a, b);
cout << ans << endl;
return 0;
}