The recursive solution is:
# Include <stdio. h>
Int inline max (int A, int B)
{
Return A> = B? A: B;
}
Int LCS (char * a, int la, char * B, int lb)
{
If (La <0 | LB <0) return 0;
If (A [la] = B [LB]) return 1 + LCS (A, la-1, B, lb-1 );
Else return max (LCS (A, la-1, B, LB), LCS (A, La, B, lb-1 ));
}
Int main ()
{
Char A [1024];
Char B [1024];
Int la, Lb;
While (1)
{
Printf (":-> ");
If (fgets (A, 1024, stdin) <= 0) break;
La = strlen (a)-2;
Printf (":-> ");
If (fgets (B, 1024, stdin) <= 0) break;
Lb = strlen (B)-2;
Printf (":-> common length is: % d", LCS (A, La, B, LB ));
}
// Printf ("the common length is: % d", LCS (A, La, B, LB ));
Return 0;
}
This solution is too inefficient and can be solved using dynamic planning. The implementation code is as follows:
# Include <stdio. h>
# Include <string. h>
Int commstr (char * str1, char * str2)
/* Returns the longest common string length of str1 and str2 */
{
Int len1 = strlen (str1), len2 = strlen (str2), row, Col, max = 0;
Int ** pF = new int * [len1 + 1]; // dynamically allocates a two-dimensional array as the auxiliary space
For (ROW = 0; row <len1 + 1; row ++)
PF [row] = new int [len2 + 1];
// Assign an initial value to an array
For (ROW = 0; row <len1 + 1; row ++)
PF [row] [0] = 0;
For (COL = 0; Col <len2 + 1; Col ++)
PF [0] [col] = 0;
For (ROW = 1; row <= len1; row ++)
For (COL = 1; Col <= len2; Col ++)
{
If (str1 [row-1] = str2 [col-1])
{
PF [row] [col] = pf [row-1] [col-1] + 1;
Max = pf [row] [col]> Max? PF [row] [col]: Max;
}
Else
PF [row] [col] = 0;
}
// Reclaim space
For (ROW = 0; row <len1 + 1; row ++)
Delete [] pf [row];
Delete [] PF;
Return Max;
}
Int main (INT argc, char ** argv)
{
If (argc> = 3)
{
Printf ("string: 1.% S 2.% s", argv [1], argv [2]);
Printf ("Max substr length: % d", commstr (argv [1], argv [2]);
}
Return 0;
}