1class Solution:
2 def longestCommonSubsequence(self, text1: str, text2: str) -> int:
3 """
4 text1: horizontally
5 text2: vertically
6 """
7 dp = [[0 for _ in range(len(text1)+1)] for _ in range(len(text2)+1)]
8
9 for row in range(1, len(text2)+1):
10 for col in range(1, len(text1)+1):
11 if text2[row-1]==text1[col-1]:
12 dp[row][col] = 1+ dp[row-1][col-1]
13 else:
14 dp[row][col] = max(dp[row-1][col], dp[row][col-1])
15 return dp[len(text2)][len(text1)]
1#include<bits/stdc++.h>
2using namespace std;
3
4const int MAX = 1001;
5
6int dp[MAX][MAX];
7bool visited[MAX][MAX];
8int x, y;
9string s1, s2;
10
11int lcs(int i, int j)
12{
13 if(i == x || j == y)
14 return 0;
15
16 if(visited[i][j])
17 return dp[i][j];
18
19 visited[i][j] = true;
20 int ans = 0;
21 if(s1[i] == s2[j])
22 {
23 ans = max(ans, 1+lcs(i+1, j+1));
24 }
25 else
26 {
27 ans = max(ans, lcs(i+1, j));
28 ans = max(ans, lcs(i, j+1));
29 }
30
31 dp[i][j] = ans;
32 return ans;
33}
34
35int main()
36{
37 cin >> x >> y;
38 cin >> s1 >> s2;
39
40 for(int i=0; i<=x; i++)
41 {
42 for(int j=0; j<=y; j++)
43 {
44 visited[i][j] = false;
45 }
46 }
47
48 cout << lcs(0, 0);
49 return 0;
50}
51
1int maxSubsequenceSubstring(char x[], char y[],
2 int n, int m)
3{
4 int dp[MAX][MAX];
5
6 // Initialize the dp[][] to 0.
7 for (int i = 0; i <= m; i++)
8 for (int j = 0; j <= n; j++)
9 dp[i][j] = 0;
10
11 // Calculating value for each element.
12 for (int i = 1; i <= m; i++) {
13 for (int j = 1; j <= n; j++) {
14
15 // If alphabet of string X and Y are
16 // equal make dp[i][j] = 1 + dp[i-1][j-1]
17 if (x[j - 1] == y[i - 1])
18 dp[i][j] = 1 + dp[i - 1][j - 1];
19
20 // Else copy the previous value in the
21 // row i.e dp[i-1][j-1]
22 else
23 dp[i][j] = dp[i][j - 1];
24 }
25 }
26
27 // Finding the maximum length.
28 int ans = 0;
29 for (int i = 1; i <= m; i++)
30 ans = max(ans, dp[i][n]);
31
32 return ans;
33}