系列问题。首先,正如 templatetypedef 所说,您分配不足。
然后,正如 paddy 所说,您并没有释放 malloc 的内存。如果您需要该Y=X
行,则需要将原始 malloc 的空间地址存储在另一组变量中,以便您可以调用free
它们。
...mallocs...
int * original_y = Y;
int * original_x = X;
...body of code...
free(original_y);
free(original_x);
return X[0];
但这并没有解决您的新问题,这就是为什么代码实际上不起作用?
我承认我无法遵循您的代码(没有更多的研究),但我可以提出一种可行且更易于理解的算法。这可能有点伪代码并且不是特别有效,但第一步是正确的。我稍后列出了一些优化。
int lcs(char * A, char * B)
{
int length_a = strlen(A);
int length_b = strlen(B);
// these hold the position in A of the longest common substring
int longest_found_length = 0;
// go through each substring of one of the strings (doesn't matter which, you could pick the shorter one if you want)
char * candidate_substring = malloc(sizeof(char) * length_a + 1);
for (int start_position = 0; start_position < length_a; start_position++) {
for (int end_position = start_position; end_position < length_a; end_position++) {
int substring_length = end_position - start_position + 1;
// make a null-terminated copy of the substring to look for in the other string
strncpy(candidate_substring, &(A[start_position]), substring_length);
if (strstr(B, candidate_substring) != NULL) {
longest_found_length = substring_length;
}
}
}
free(candidate_substring);
return longest_found_length;
}
你可以做一些不同的优化:
// if this can't be longer, then don't bother checking it. You can play games with the for loop to not have this happen, but it's more complicated.
if (substring_length <= longest_found_index) {
continue;
}
和
// there are more optimizations you could do to this, but don't check
// the substring if it's longer than b, since b can't contain it.
if (substring_length > length_b) {
continue;
}
和
if (strstr(B, candidate_substring) != NULL) {
longest_found_length = end_position - start_position + 1;
} else {
// if nothing contains the shorter string, then nothing can contain the longer one, so skip checking longer strings with the same starting character
break; // skip out of inner loop to next iteration of start_position
}
您可以使用 和 字符进行字符交换,而不是将每个候选子字符串复制到新end_position + 1
字符串NUL
。然后,在 b 中查找该子字符串后,将原始字符end_position+1
换回。这会快得多,但会使实现稍微复杂一些。