Problem : Given two sequence of elements (usually characters), find the longest subsequence present in both of them. A subsequence is a sequence that appears in the same order,as appeared in original sequence's .
Example : Strings "abc","abd","cde" are sub-sequence of string "abcdefghi".
Solution : With dynamic programming we can solve this problem in O(m*n) time , where m is length of first sequence and n is length of second sequence.
C++ Solution :
char *get_lcs(char *first_str,char *sec_str,int str_len1,int str_len2)
{
int m,n,i,j;
char temp_lcs[100][100];
int temp_len_lcs[100][100];
char ret_str[100];
memset(temp_lcs,'\0',sizeof(temp_lcs));
memset(temp_len_lcs,0,sizeof(temp_len_lcs));
for(m = 0;m<str_len1;m++)
{
temp_len_lcs[m][0] = 0;
}
for(n = 0;n<str_len2+1;n++)
{
temp_len_lcs[0][n] = 0;
}
for(m = 0;m<str_len1;m++)
{
for(n = 1;n<str_len2+1;n++)
{
if(first_str[m] == sec_str[n-1])
{
temp_len_lcs[m][n] = temp_len_lcs[m-1][n-2] + 1;
temp_lcs[m][n-1] = '=';
}
else
{
if(temp_len_lcs[m-1][n-1] >= temp_len_lcs[m][n-2])
{
temp_len_lcs[m][n-1] = temp_len_lcs[m-1][n-1];
temp_lcs[m][n-1] = '+';
}
else
{
temp_len_lcs[m][n-1] = temp_len_lcs[m][n-2];
temp_lcs[m][n-1] = '-';
}
}
}
}
memset(ret_str,'\0',sizeof(ret_str));
i = m;
j = n;
while(1)
{
if(i == 0 || j == 0)
{
break;
}
else
{
if(temp_lcs[i-1][j-1] == '=')
{
i--;
j--;
strncat(ret_str,(first_str+i),1);
}
else if(temp_lcs[i-1][j-1] == '+')
{
--i;
}
else
{
--j;
}
}
}
return strrev(ret_str);
}
Usage :
Call this function from main like this
int main(void)
{
char first_str[100];
char sec_str[100];
char lcs[100];
memset(first_str,'\0',sizeof(first_str));
memset(sec_str,'\0',sizeof(sec_str));
memset(lcs,'\0',sizeof(lcs));
scanf("%s",first_str);
scanf("%s",sec_str);
strcpy(lcs,get_lcs(first_str,sec_str,strlen(first_str),strlen(sec_str)));
std::cout<<lcs<<"\n";
int a;
std::cin>>a;
return 0;
}