/*
主题:查找两个字符串中的最大公共子串
*/
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
char *commonString(char *str1, char *str2)
{
int i, j;
char *shortStr, *longStr, *subStr;
//判断字符串的有效性
if (NULL == str1 || NULL == str2)
{
return NULL;
}
if (strlen(str1) <= strlen(str2))
{
shortStr = str1;
longStr = str2;
}
else
{
shortStr = str2;
longStr = str1;
}
/*
如果在长的字符串中能寻找短的字符串,返回短字符串
*/
if (strstr(longStr, shortStr) != NULL)
{
return shortStr;
}
subStr = (char *) malloc((strlen(shortStr) + 1) * sizeof(char));
for (i = strlen(shortStr) - 1; i > 0; i--)
{
for (j = 0; j <= strlen(shortStr) - i; j++)
{
/*
将短字符串的一部分复制到substr;其长度逐渐减小
*/
memcpy(subStr, &shortStr[j], i);
subStr[i] = '\0';
printf("%s\n", subStr);
//如果在longStr中能找到subStr则返回subStr
if (strstr(longStr, subStr) != NULL)
{
return subStr;
}
}
}
return NULL;
}
int main(void)
{
char *str1 = (char *)malloc(256);
char *str2 = (char *)malloc(256);
char *common = NULL;
gets(str1);
gets(str2);
common = commonString(str2, str1);
printf("the longst common string is: %s", common);
return 0;
}