Longest common sub-sequence (LCS)

Source: Internet
Author: User

Note the difference between the longest common substring (longest commonsubstring) and the longest common subsequence (Longestcommon subsequence, LCS): a substring (Substring) is a contiguous part of a string, A subsequence (subsequence) is a new sequence obtained by removing any element from a sequence without altering the order of the sequence, or, more simply, the position of the character of the former (substring) must be continuous, and the latter (the subsequence LCS). For example, the longest common substring of the string ACDFG with AKDFC is DF, and their longest common subsequence is ADF. LCS can be solved by using dynamic programming.

Studied http://blog.csdn.net/v_july_v/article/details/6695482 's ideas and wrote an O (MN) algorithm

#include <iostream>#include<algorithm>#include<string>#include<cstdio>#defineN 105using namespacestd;intDp[n][n];strings[2];ints1,s2;intMax (intAintb) {    returnA>b?a:b;}BOOLSame (intIintj) {    if(s[0][i]==s[1][j])return true; return false;}//If you need to output a combination of two strings based on the longest common string, refer to the AC Code of hdu1503stringSolve ()//output the longest common string{S1=-1, s2=-1;  for(intI=0; i<n; i++) for(intj=0; j<n; J + +) dp[i][j]=0;  for(inti=s[0].length ()-1; i>=0; i--)//top-down traversal for easy restore in sequential restore         for(intj=s[1].length ()-1; j>=0; j--)        {            if(Same (i,j)) {Dp[i][j]=dp[i+1][j+1]+1; if(s1==-1) s1=i; S2=J;
} ElseDp[i][j]=max (dp[i+1][j],dp[i][j+1]); } stringans=""; intI=0, j=0; while(i<s[0].length () &&j<s[1].length ()) {if(Same (I,j)) ans+=s[0][i],i++,j++; Else { if(dp[i][j+1]>dp[i+1][j]) J++; ElseI++; } } returnans;}intMain () { while(cin>>s[0]>>s[1]) {cout<<solve () <<Endl; } return 0;}

Longest common sub-sequence (LCS)

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.