请教高人一个C的最大公子串的编程问题

来源:百度知道 编辑:UC知道 时间:2024/05/08 09:08:10
#include<iostream.h>
#include<string.h>
int maxlen = 0;
char **r1, **r2;
char a[]="abcd",b[]="abc";
//r1=new char;
//r2=new char;
void GetCommon( char *s1, char *s2)
{

int len1 = strlen(s1);
int len2 = strlen(s2);

for(int i = 0; i < len1; i++)
{
for(int j = 0; j < len2; j++)
{
if(s1[i] == s2[j])
{
int as = i,bs = j, count = 1;
while(as + 1 < len1 && bs + 1 < len2 && s1[++as] == s2[++bs])
count++;
if(count > maxlen)
{ // s1=a;
//s2=b;
maxlen = count;
*r1 = s1 + i;
*r2 = s2+ j;
}
}
}
}
//return *r1;
}
main()
{
// char *a="abcdef", *b="defghi";
// char **c,**d;
// char *c;

GetCommon(a,b);
for(int i=0;i<maxlen;i++)
cout&

你的程序基本没什么问题,不过要注意代码规范,声明都要放在最开始,我用c跟你调试了一下,不知道对你有没有用。程序输出为def。其中**r1和**r2改为*r1和*r2要更好一些,二重指针这里基本用不上的。
#include <string.h>
#include <stdio.h>

int maxlen = 0;
char **r1, **r2;
char a[]="abcd",b[]="abc";

void GetCommon( char *s1, char *s2)
{
int i,j,as,bs,count;
int len1 = strlen(s1);
int len2 = strlen(s2);

for(i = 0; i < len1; i++)
{
for(j = 0; j < len2; j++)
{
if(s1[i] == s2[j])
{
as = i;
bs = j;
count = 1;
while(as + 1 < len1 && bs + 1 < len2 && s1[++as] == s2[++bs])
count++;
if(count > maxlen)
{
/*s1=a;s2=b;*/
maxlen = count;
*r1 = s1 + i;