使用C语言,编写函数,查找两个字符串中最大公共字串,如:字符串A="abcdefg",字符串B="cdeab",做大公共字串为“cde”。
思路:先确定短的字符串short_str和长的字符串long_str,用short_str在long_str中匹配,如果没匹配到,将short_str最后一个字符置'\0',再去匹配,直到匹配到了返回字符串指针。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* get_common_str(char *pStr1, char *pStr2)
{
if ((pStr1 == NULL) || (pStr2 == NULL)) {
return NULL;
}
char* pShortStr = NULL, *pLongStr = NULL;
if (strlen(pStr1) < strlen(pStr2)) {
pShortStr = pStr1;
pLongStr = pStr2;
} else {
pShortStr = pStr2;
pLongStr = pStr1;
}
if (strstr(pLongStr, pShortStr) != NULL) {
return pShortStr;
} else {
for (int i = strlen(pShortStr) - 1; i >= 0; --i) {
pShortStr[i] = '\0';
if (strstr(pLongStr, pShortStr) != NULL) {
return pShortStr;
}
}
}
return NULL;
}
int main()
{
//最大字串:cde
char szBuf1[32] = { 0 };
strcpy(szBuf1, "abcdefg");
char szBuf2[32] = { 0 };
strcpy(szBuf2, "cdeab");
char* pResult = get_common_str(szBuf1, szBuf2);
printf("pResult=[%s]\n", pResult);
return 0;
}
程序运行结果如下: