/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
#include <stdio.h>
char* LCS(char* str1, char* str2 ) {
// write code here
int l1 = strlen(str1);
int l2 = strlen(str2);
int** dp = (int**)malloc(sizeof(int*) * l1);
int max = 0;
int endPosition = 0;
for(int i = 0; i < l1; i++) {
dp[i] = (int*)malloc(sizeof(int) * l2);
for(int j = 0; j < l2; j++) {
if(str1[i] == str2[j]) {
if(i == 0 || j == 0) dp[i][j] = 1;
else {
dp[i][j] = dp[i - 1][j - 1] + 1;
if(dp[i][j] > max) {
max = dp[i][j];
endPosition = i;
}
}
} else {
dp[i][j] = 0;
}
}
}
char* result = (char*)malloc(sizeof(char) * max);
if(result == NULL) {
perror("内存分配失败");
exit(1);
}
strncpy(result, str1 + endPosition - max + 1, max);
result[max] = '\0';
for(int i = 0; i < l1; i++) {
free(dp[i]);
}
free(dp);
return result;
}