Longest Common substring (LCS)
Find the longest common substring of two strings, which must be continuous in the original string. In fact, this is a sequential decision-making problem, which can be solved using dynamic planning. We use a two-dimensional matrix to record the intermediate results. How to construct this two-dimensional matrix? For example: "Bab" and "Caba" (of course, we can see at a glance that the longest public substring is "ba" or "AB ")
B A B
C 0 0 0
A 0 1 0
B 1 0 1
A 0 1 0
We can see that the longest diagonal line of the matrix can find the longest common substring.
However, finding the longest diagonal line composed of 1 on a two-dimensional matrix is also time-consuming. The following improvements: when the matrix is filled with 1, make it equal to the element in the upper left corner of the matrix plus 1.
B A B
C 0 0 0
A 0 1 0
B 1 0 2
A 0 2 0
In this way, the maximum element in the matrix is the length of the longest common substring.
In the process of constructing the two-dimensional matrix, the previous row of the matrix is useless because a row of the matrix is obtained. In fact, the one-dimensional array can be used in the program to replace the matrix.
Void getmaxlenchildstr (char * str1, int N1, char * str2, int N2, char * res) {int max = 0; // maximum value int * pre = new int [n2] in the matrix element; // save the last int * cur = new int [n2] in the matrix; // The current row for (INT I = 0; I <N2; I ++) // initialize {pre [I] = 0 ;}for (INT I = 0; I <N2; I ++) {cur [I] = 0;} int Pos = 0; // the maximum value of the matrix element in the column for (INT I = 0; I <N1; I ++) {for (Int J = 0; j <N2; j ++) {If (str1 [I] = str2 [J]) {If (j = 0) {cur [J] = 1;} else {cur [J] = pre [J-1] + 1 ;} if (cur [J]> MAX) {max = cur [J]; Pos = J ;}}for (INT I = 0; I <N2; I ++) {pre [I] = cur [I] ;}} strncpy (Res, str2 + pos-MAX + 1, max) ;} int main () {char str2 [] = "ABA"; char str1 [] = "cabda"; char res [5] = {'\ 0'}; getmaxlenchildstr (str1, 5, str2, 3, Res); Return 0 ;}Http://www.cnblogs.com/zhangchaoyang/articles/2012070.html#3022705
Longest Common substring (LCS)