Problem: There are two strings. We need to find their longest public substrings. For example, the regression and express strings, whose substrings are E and RESS, then their longest common strings are RESS.
Solution:
We use a two-dimensional array to record the matching conditions between two strings. If the string str1 length is len1 and the string str2 length is len2, the array can be set to table [len1] [len2].
For each element in the array table [I] [J], when the value of the corresponding position of the string is consistent (str1 [I] = str2 [J]) is 1, 0 for inconsistency. After all the comparisons are completed, the maximum number of consecutive occurrences of 1 on the diagonal line in the array is the length of their continuous longest public substrings.
However, because we are looking for the longest common string values, and we need to calculate the number of consecutive occurrences of 1 on the diagonal line. We can improve the algorithm: When the value at the corresponding position of the string is consistent (str1 [I] = str2 [J]), table [I] [J] = table [I-1] [J-1] + 1. In this way, we can easily get the longest public substring length. At the same time, we can record the sequence number of I or J when table [I] [J] is the largest, so that we can get the location of the longest common substring.
The Code is as follows:
1 void lcs(char* str1, char* str2) 2 { 3 // get length of the strings 4 int len1 = strlen(str1); 5 int len2 = strlen(str2); 6 // build 2-D array 7 vector<vector<int> > arr; 8 arr.resize(len1); 9 for(int i = 0; i < len1; i++) {10 arr[i].resize(len2);11 }12 // compare13 int maxLen = 0;14 int maxIdx = 0;15 int i;16 int j;17 i = 0;18 for (j = 0; j < len2; j++) {19 if (str2[j] == str1[i]) {20 arr[i][j] = 1;21 }22 }23 j = 0;24 for (i = 0; i < len1; i++) {25 if (str2[j] == str1[i]) {26 arr[i][j] = 1;27 }28 }29 for (i = 1; i < len1; i++) {30 for (j = 1; j < len2; j++) {31 if (str2[j] == str1[i]) {32 arr[i][j] = arr[i-1][j-1] + 1;33 if (arr[i][j] > maxLen) {34 maxLen = arr[i][j];35 maxIdx = i;36 }37 }38 }39 }40 // output lcs41 char *result = (char *) malloc(maxLen+1);42 memcpy(result, str1 + maxIdx - maxLen + 1, maxLen);43 result[maxLen] = ‘\0‘;44 printf("str1:%s\n", str1);45 printf("str2:%s\n", str2);46 printf("result:%s\n", result);47 }
Search for the longest public substring