首页 > 代码库 > 两个字符串最长相同部分
两个字符串最长相同部分
/*功能,给出两个字符串,找出一处最长相同的部分*/
char *longestsame(char*,char*);
int main()
{
char *a = "aaaabbcccc";
char *b = "bccc";
char *ret = longestsame(a,b);
printf("%s\n",ret);
}
char *longestsame(char*a, char* b)
{
char *longer;
char *shorter;
if(strlen(a) > strlen(b))
{longer = a, shorter = b;}
else
{ longer = b, shorter = a;}
unsigned int size = strlen(shorter);
unsigned int lsize = strlen(longer);
for(int i = size; i > 1; i--)
{
for(int j = 0; j <= size - i; j++)
{
for(int k = 0; k <= lsize - i ; k++)
{
if(0 == strncmp((shorter+j),(longer+k),i))
{
char* st = (char*)calloc(sizeof(char)*i+1,1);
strncpy(st,shorter+j,i);
return st;
}
}
}
}
return NULL;
}
两个字符串最长相同部分