Longest Common subsequence

Source: Internet
Author: User
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.