xxxxxxxxxx
class Solution
{
//Function to find the length of longest common subsequence in two strings.
static int lcs(int x, int y, String s1, String s2)
{
int dp[][] = new int[x+1][y+1];
for(int i=0;i<=x;i++)
{
for (int j=0;j<=y;j++)
{
dp[i][j]=-1;
}
}
return lcshelper(x,y,s1,s2, dp);
}
static int lcshelper(int m,int n,String x, String y, int[][] dp)
{
if(m==0 || n==0)
return 0;
if (dp[m][n]!= -1)
return dp[m][n];
if (x.charAt(m-1)==y.charAt(n-1))
dp[m][n] = 1+lcshelper(m-1,n-1,x,y, dp);
else
dp[m][n]= Math.max(lcshelper(m-1,n,x,y,dp), lcshelper(m,n-1,x,y,dp));
return dp[m][n];
}
}
xxxxxxxxxx
int LongestRepeatingSubsequence(string str){
// Code here
int n=str.length();
vector<int> prev(n+1,0), cur(n+1,0);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(str[i-1]==str[j-1])cur[j]=1+prev[j-1];
else cur[j]=max(cur[j-1], prev[j]);
}
prev=cur;
}
return cur[n];
}
xxxxxxxxxx
#include <bits/stdc++.h>
using namespace std;
void lcs(string s1, string s2) {
int n = s1.size();
int m = s2.size();
vector < vector < int >> dp(n + 1, vector < int > (m + 1, 0));
for (int i = 0; i <= n; i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= m; i++) {
dp[0][i] = 0;
}
for (int ind1 = 1; ind1 <= n; ind1++) {
for (int ind2 = 1; ind2 <= m; ind2++) {
if (s1[ind1 - 1] == s2[ind2 - 1])
dp[ind1][ind2] = 1 + dp[ind1 - 1][ind2 - 1];
else
dp[ind1][ind2] = 0 + max(dp[ind1 - 1][ind2], dp[ind1][ind2 - 1]);
}
}
int len = dp[n][m];
int i = n;
int j = m;
int index = len - 1;
string str = "";
for (int k = 1; k <= len; k++) {
str += "$"; // dummy string
}
while (i > 0 && j > 0) {
if (s1[i - 1] == s2[j - 1]) {
str[index] = s1[i - 1];
index--;
i--;
j--;
} else if (s1[i - 1] > s2[j - 1]) {
i--;
} else j--;
}
cout << str;
}
int main() {
string s1 = "abcde";
string s2 = "bdgek";
cout << "The Longest Common Subsequence is ";
lcs(s1, s2);
}