Longest Common subsequence of LCS and LCS common subsequence

Source: Internet
Author: User

Longest Common subsequence of LCS and LCS common subsequence

Problem: The Longest Common subsequence does not require that the obtained string be continuous in the given string. For example, the input two strings ABCBDAB and BDCABA, And the strings BCBA and BDAB are both their public longest headers.

This is a dynamic planning problem.

Answer: set sequence X = <x0, x1 ,..., xm> and Y = <y0, y1 ,..., one of the longest common subsequences of yn> is Z = <z0, z1 ,..., zk>, then:

1) if xm = yn, there must be zk = xm = yn, then zk-1 is the longest common subsequence of xm-1 and yn-1;

2) If xm =yn and zk =xm, Z is the longest common subsequence of Xm-1 and Y;

3) If xm =yn and zk =yn, Z is the longest common subsequence of X and Yn-1;

That is to say:

When xm = yn, LCS (Xm, Yn) = LCS (Xm-1, Yn-1) + 1;

When xm =yn, LCS (Xm, yn) = max {LCS (Xm-1, Yn), LCS (Xm, Yn-1 )};

When X and Y are empty, the LCS length is 0;


1 # include <iostream> 2 # include <cmath> 3 # define INF 9999999 4 using namespace std; 5 int a [100] [100]; // record the computed subproblem 6 int fun (const char * str1, const char * str2, int I, int j) 7 {8 if (a [I] [j] <INF) return a [I] [j]; // 9 else if (I = 0 | j = 0) a [I] [j] = 0; 10 else if (str1 [I-1] = str2 [J-1]) a [I] [j] = fun (str1, str2, I-1, J-1) + 1; 11 else a [I] [j] = max (fun (str1, str2, I-1, j), fun (str1, str2, I, J-1 )); 12 return a [I] [j]; 13} 14 int longest (const char * str1, const char * str2) 15 {16 int m = strlen (str1 ); 17 int n = strlen (str2); 18 memset (a, INF, sizeof (a); // set element a to INF19 return fun (str1, str2, m, n); 20} 21 int main () 22 {23 char * str1 = new char [100], * str2 = new char [100]; 24 cout <"input first string:"; 25 cin> str1; 26 cout <"input second string:"; 27 cin> str2; 28 cout <"the longest length of sunstring is:"; 29 cout <longest (str1, str2) <endl; 30 delete [] str1; 31 delete [] str2; 32}




Related Article

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.