LCS Algorithm Implementation

Source: Internet
Author: User

Dynamic Programming algorithm

#include <iostream>#include<string.h>#include<algorithm>#include<math.h>using namespacestd;#defineMaxstrlen 20intLcs (CharX[],CharY[],intPath[][maxstrlen])//To find the longest common subsequence of the sequence x and Y, the path save route points to facilitate printing of common sub-sequences{    intI, J; intLen1=strlen (x)-1; intLen2=strlen (Y)-1; int**c=New int*[len1+1];  for(i=0; i<=len1; i++) C[i]=New int[len2+1];  for(i=0; i<=len1; i++) c[i][0]=0;  for(i=0; i<=len2; i++) c[0][i]=0;  for(i=1; i<=len1; i++)         for(j=1; j<=len2; J + +)//starting from x[1],y[1]        {            if(x[i]==Y[j]) {C[i][j]=c[i-1][j-1]+1; PATH[I][J]=1; }            Else if(c[i-1][j]>=c[i][j-1]) {C[i][j]=c[i-1][j]; PATH[I][J]=2; }            Else{C[i][j]=c[i][j-1]; PATH[I][J]=3; }                }                returnc[len1][len2];}voidPrintlcs (intIintJCharX[],intPath[][maxstrlen])//print the longest common sub-sequence{    if(i==0|| j==0)        return; if(path[i][j]==1) {Printlcs (i-1, J-1, x, Path); cout<<X[i]; }    Else if(path[i][j]==2) Printlcs (i-1, J, x, Path); ElsePrintlcs (i, J-1, x, Path); }voidMain () {CharA[maxstrlen]; CharB[maxstrlen]; intPath[maxstrlen][maxstrlen]; Gets (a+1);//A[0] Not counting, starting from a[1]Gets (b +1);//B[0] Not counting, starting from b[1]cout<<lcs (A, B, path) <<Endl; cout<<"the longest common subsequence:"; Printlcs (Strlen (a)-1, strlen (b)-1, A, path); cout<<Endl; }

Recursive algorithm

#include <iostream>using namespacestd;#defineMaxstrlen 20//Recursive algorithmintLcs (Char*STR1,Char*str2) {    if(*str1==' /'|| *str2==' /')        return 0; if(*str1==*str2)returnLcs (str1+1, str2+1)+1; Else if(Lcs (str1+1, str2) >lcs (str1, str2+1))        returnLcs (str1+1, STR2); Else        returnLcs (STR1, str2+1); }voidMain () {CharA[maxstrlen]; CharB[maxstrlen];    Gets (a);    Gets (b); cout<<lcs (A, b) <<Endl; }

LCS Algorithm Implementation

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.