The longest common substring of two strings, LCS (longest common substring)Algorithm
Reference http://www.5do8.com/blog/doc/569/index.aspx
For the LCS algorithm of multiple strings, refer toProgramIt seems that there is a problem
Two LCS programs
# Include < Stdio. h >
# Include < String . H >
// Return the start position in argb
// N: the length of the LCS
Const Char * Getsamestring ( Char Const * Arga, Char Const * Argb, Int * N) {
Int N1 = Strlen (arga );
Int N2 = Strlen (argb );
If (N1 = 0 | N2 = 0 ) Return 0 ;
Int * Comparearr = New Int [N2];
Int Max = 0 , Maxj = 0 ;
For ( Int Iloop = 0 ; Iloop < N1; iloop ++ ) // Note the sequence of first I and then J
{
For ( Int Jloop = N2 - 1 ; Jloop > = 0 ; Jloop -- ) // Note that the order is from large to small, so that the new and old comparearr do not affect each other during DP.
{
// This equation is dazzling and uses the DP idea. If the I of the current string 1 is equal to the J of string 2, and the I or J is 0, it is 1; otherwise, it is
Comparearr [jloop] = (Argb [jloop] = Arga [iloop]) ? (Iloop = 0 | Jloop = 0 ) ? 1 : Comparearr [jloop - 1 ] + 1 ): 0 ;
If (Comparearr [jloop] > = Max)
{
Max=Comparearr [jloop];
Maxj=Jloop;
}
}
}
If (Max > 0 )
{
*N=Max;
ReturnArgb+Maxj-Max+1;
}
Else
Return 0 ;
}
Void Main ()
{
Char * S1 = " Abcdefg " ;
Char * S2 = " Xwwdcdedjwdng " ;
Int N;
Const Char * P = Getsamestring (S1, S2, & N );
If (P)
{
Printf ("At str2's pos % d, Len % d \ n", P-S2, N );
}
Else
Printf ( " No LCS \ n " );
}