일련의 문제. 첫째, templatetypedef가 말했듯이, 당신은 미숙 한 상태입니다.
그러면 패디가 말했듯이, 당신은 당신의 malloc 된 메모리를 자유롭게하지 못합니다. Y=X
라인이 필요하면 원래의 malloc'd 스페이스 주소를 다른 변수 세트에 저장하여 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
}
, 당신은 할 수 t로 문자 교환하기 그는 end_position + 1
및 NUL
문자입니다. 그런 다음 b에서 해당 하위 문자열을 찾은 후 원래 문자 인 end_position+1
을 다시 넣습니다.이 방법은 훨씬 빠르지 만 구현이 약간 복잡합니다. templatetypedef 말한 외에도
'Y = X;'하는 방법을 정말 좋아하지 않습니다. 이것은 메모리 누수이며 버퍼 오버 플로우 가능성이 있습니다. – paddy
'valgrind'의 처음 몇 가지 오류를 보여주는 것이 현명 할 것입니다; 우리는 그것이 무엇을보고 있는지 추측해서는 안됩니다. –
실제 변수 이름을 사용하십시오. 'm'은'a_len ', n은'b_len','X'는'longestSoFar' (정확한 경우) 등이 있습니다. – djechlin