程序分析:从较短的字符串着手,对它的子串从长到短,依次与较长的字符串进行匹配。
C++代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
char* GetCommonString(char *str1, char *str2) {
if (str1 == NULL || str2 == NULL) {
return NULL;
}
char *longstr, *shortstr, *substr;
//找出两个字符串的长串和短串
if (strlen(str1) < strlen(str2)) {
longstr = str2;
shortstr = str1;
}
else {
longstr = str1;
shortstr = str2;
}
//如果短串刚好为长串的子串,直接返回
if (strstr(longstr, shortstr) != NULL) {
return shortstr;
}
//寻找两个字符串中的最大公共子串
substr = (char*)malloc(strlen(shortstr));
//控制子串个数
for (int i = strlen(shortstr) - 1; i > 0; i--) {
//控制子串位置
for (int j = 0; j <= strlen(shortstr) - i; j++) {
strncpy(substr, &shortstr[j], i);
substr[i] = '\0';
if (strstr(longstr, substr) != NULL) {
return substr;
}
}
}
if (substr != NULL) {
free(substr);
substr = NULL;
}
return NULL;
}
int main() {
char str1[50];
char str2[50];
cout << "Please input the first string:";
cin >> str1;
cout << "Please input the second string:";
cin >> str2;
cout << "The common substring is:" << GetCommonString(str1, str2) << endl;
return 0;
}
C++运行结果:
(1)找到最大公共子串
(2)若有两个及两个以上的最大公共子串,输出第一个
(3)没有公共子串