Jun 25, 2017

length of longest common subsequence of 2 strings


#include <iostream>
#include <string.h>
using namespace std;

/*

lcs(s1[1,m], s2[1,n]) = 1 + lcs(s1[1,m-1], s2[1,n-1]) 
       if s1[m] == s2[n]
 
 = max(lcs(s1[1,m-1], s2[1,n]) , lcs(s1[1,m], s2[1,n-1]) ) otherwise
*/
int max(int x, int y)
{
 return x>y?x:y; 
}
int lcs(char* s1, int m, char *s2, int n)
{
 if(m==0 || n==0)
  return 0;
  
 if(s1[m-1] == s2[n-1])
  return (1 + lcs(s1, m-1, s2, n-1));
  
 return max(lcs(s1, m-1, s2, n), lcs(s1, m, s2, n-1));
}

int lcsdp(char* s1, int m, char* s2, int n)
{
 int lcs[m+1][n+1];
 
 for(int i=0;i<=m; i++)
  for(int j=0; j<=n; j++)
   lcs[i][j] = 0;
 
 for(int i=1;i<=m; i++)
 {
  for(int j=1; j<=n; j++)
  {
   if(s1[i-1] == s2[j-1])
   {
    lcs[i][j] = 1 + lcs[i-1][j-1];
    //cout << s1[i-1] << " ";
   }
   else
   {
    lcs[i][j] = max(lcs[i][j-1], lcs[i-1][j]);
    //cout << i << " " << j << " lcs:" << lcs[i][j] <<endl;
   }
  }
 }
 
 for(int i=0; i<=m; i++)
 {
  for(int j=0; j<=n;j++)
  {
   cout << lcs[i][j] << " ";
  }
  cout << endl;
 }
 return lcs[m][n];
}

int lcsdp2(char* s1, int m, char* s2, int n)
{
 int lcs[m+1][n+1];
 
 for(int i=0;i<=m; i++)
  for(int j=0; j<=n; j++)
   lcs[i][j] = 0;
 
 for(int i=1;i<=m; i++)
 {
  for(int j=1; j<=n; j++)
  {
   if(s1[i-1] == s2[j-1] & i!=j)
   {
    lcs[i][j] = 1 + lcs[i-1][j-1];
    //cout << i << " -" << j << " lcs:" << lcs[i][j] <<endl;
   }
   else
   {
    lcs[i][j] = max(lcs[i][j-1], lcs[i-1][j]);
    //cout << i << " " << j << " lcs:" << lcs[i][j] <<endl;
   }
  }
 }
 
 for(int i=0; i<=m; i++)
 {
  for(int j=0; j<=n;j++)
  {
   cout << lcs[i][j] << " ";
  }
  cout << endl;
 }
 return lcs[m][n];
}

int main() {
 // your code goes here
 char s1[100], s2[100];
 cin >> s1;
 cin >> s2;
 cout << "length of longest increasing subsequence of "<<\
 s1 << " and " << s2 << " is: " << lcsdp(s1,strlen(s1),s2,strlen(s2));
 return 0;
}

input:
abba
acbfabc

output:
length of longest increasing subsequence of abba and acbfabc is: 3

No comments: