Description: a query and a text are all composed of lowercase letters. It is required to find the length of the longest consecutive letter sequence that appears continuously in the query in the same order in text. For example, if the query is "acbac" and the text is "acaccbabb", the "CBA" in the text is the longest sequential letter sequence that appears in the query. Therefore, the returned result must be 3 characters long. Pay attention to program efficiency.
Idea: Use a matrix to record the matching conditions between two characters in all positions in two strings. If it matches, it is 1; otherwise, it is 0. Then we can find the longest 1 series of diagonal lines. The corresponding position is the longest position matching the substring.
When matching a character, it is not simply to assign 1 to the corresponding element, but to add 1 to the value of the element in the upper left corner. We use two marking variables to mark the position of the element with the largest median value in the Matrix. During the matrix generation process, we can determine whether the value of the currently generated element is the largest. Based on this, we can change the value of the marking variable, by the time the matrix is complete, the longest position and length of the matched substring have come out.
Example:
A C B A C
A 1 0 0 1 0
C 0 2 0 0 2
A 1 0 0 1 0
C 0 2 0 0 2
C 0 1 0 0 1
B 0 0 2 0 0
A 1 0 0 3 0
B 0 0 1 0 0
B 0 0 1 0 0
(The longest public substring in red)
# Include <cstring> # include <cstdio> # define M 1010int LCS (char Query [], char text []) {int len_query = strlen (query ), len_text = strlen (text); // array C Record matching, simulating the two-dimensional matrix char C [len_text]; int Len, I, j; Len = 0; for (I = 0; I <len_query; I ++) {// The elements of the previous array are not reversed, because the following elements need to be calculated for (j = len_text-1; j> = 0; j --) {If (Query [I] = text [J]) based on the previous Element {if (I = 0 | j = 0) C [J] = 1; else C [J] = C [J-1] + 1 ;} else C [J] = 0; If (C [J]> Len) Len = C [J] ;}} return Len ;} int main () {char str1 [m], str2 [m]; printf ("Enter the string query:"); fgets (str1, 1000, stdin); printf ("Enter the string text: "); fgets (str2, 1000, stdin); printf (" Length: "); printf (" % d \ n ", LCS (str1, str2 )); return 0 ;}
Longest public substring of Alibaba written examination