Substring - Subsequence problem

PROBLEM :
Manoj, Vinoj and Jegan are the famous coders of TCE. One fine day Vinoj and Jegan challenge Manoj to solve a puzzle. That is Vinoj will select one string A. Similarly Jegan will choose one string B with the same size. You need to help Manoj to find the longest subsequence X of a string A which is a substring Y of a string B.

Example
A : ABCD
B : BACDBDCD
The answer would be 3 as because 'ACD' is the longest subsequence of A which is also a substring of B.

Input:
The first line of input contains an integer T. Then T test cases follow. Each test case contains two space separated strings A and B.

Output:
For each test case in a new line print the required output.

Constraints:
1<=T<=12
1<=Length of strings <=100

Example:
Input:
2
ABCD BACDBDCD
A A

Output:
3
1

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>
int Subsequence(string ,string ) ;
int main()
{
int t ;
string s1,s2 ;
cin>>t ;
while(t--)
{
   cin>>s1>>s2 ;
   cout<<Subsequence(s1,s2)<<endl ;
}
return 0;
}

int Subsequence(string s1,string s2)
{
    int l1,l2,max,i,j ;
    l1=s1.length() ;
    l2=s2.length() ;
   
    int mat[l2+1][l1+1] ;
    max=0 ;
   
    for(i=0;i<=l2;i++)
        mat[i][0]=0 ;
       
    for(i=0;i<=l1;i++)
        mat[0][i]=0 ;
       
    for(i=1;i<=l2;i++)
    {
        for(j=1;j<=l1;j++)
        {
            if(s2[i-1]==s1[j-1])
                mat[i][j]=mat[i-1][j-1]+1 ;
            else
                mat[i][j]=mat[i][j-1] ;
               
            if(mat[i][j]>max)
                max=mat[i][j] ;
        }
    }
    return max ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )