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)