#include <stdio.h>
#include <string.h>
#define MAXLINE 4096
void max_sub_str(const char str1[], const char str2[], char max_sub_str[])
{
int max_len = 1;
int pos = 0;
for (int cur1 = 0; str1[cur1] != '\0'; cur1++) {
for(int cur2 = 0; str2[cur2] != '\0'; cur2++) {
while((strncmp(str1 + cur1, str2 + cur2, max_len) == 0) && *(str2 + cur2 + max_len - 1) != '\0') {
max_len++;
pos = cur2;
}
}
}
strncpy(max_sub_str, str2 + pos, max_len);
}
int main()
{
char str1[] = "abcdefgabchaha";
char str2[] = "adfefghaha";
char result[MAXLINE];
max_sub_str(str1, str2, result);
printf("result = %s\n", result);
return 0;
}
运行结果如下:
cheny@cheny-laptop:~/string$ ./max_sub_str
result = haha
这道题时间复杂度有点高,不过小弟也实在是想不出什么好的办法来解决,这题有一个地方需要注意一下:
while((strncmp(str1 + cur1, str2 + cur2, max_len) == 0) && *(str2 + cur2 + max_len - 1) != '\0')
在用strncmp做字符串比较的时候,一定要判断一下字符串有没有结束,不然的话如果字符数组很长,这个while会一直把数组跑完才结束,例如:
int n;
int ret;
char str1[10000] = "abc";
char str2[10000] = "abc";
ret = strncmp(str1, str2, n);
这里面ret会在0<n<10000的时候都是等于0的,这样子会做一些无意义的运算,其实你想要的结果早就结束了,n = 3即可,写的不好请大家指正,谢谢!