2019.3.14
编程查找两个字符串中的最大公共子串
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190314214827634.jpg)
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
char * CommonStr(char* str1, char* str2)
{
char *shortStr = str1;
char *longStr = str2;
char *subStr;
subStr = (char*)malloc(sizeof(shortStr));
if (str1 == NULL || str2 == NULL){
return NULL;
}
if (strlen(str1) > strlen(str2)){
shortStr = str2;
longStr = str1;
}
for (int i = strlen(shortStr); i > 0; i--)
{
for (int j = 0; j <= strlen(shortStr) - i; j++)
{
memcpy(subStr, &shortStr[j], i);
subStr[i] = '\0';
if (strstr(longStr, subStr) != NULL)
{
return subStr;
}
}
}
}
int main()
{
char *str1 = (char *)malloc(256);
char *str2 = (char *)malloc(256);
char *common = NULL;
cin >> str1;
cout << endl;
cin >> str2;
cout << endl;
common = CommonStr(str2, str1);
printf("the longest common string is %s\n", common);
system("pause");
return 0;
}