求两个字符串的最长连续子串

    // 编程实现:找出两个字符串中最大公共子字符串,如"abccade","dgcadde"的最大子串为"cad"
    // 采用后缀数组,利用归并排序当中的思想。
    //
    class CMaxCommon:public CTest
    {
    public:
        static int com(const void *s1,const void *s2)
        {
            return strcmp(*(char**)s1,*(char **)s2);
        }
        int get(char *s1,char *s2,char *buf)
        {
            char *p=s1;
            while(*s1!='\0'&&*s2!='\0'&&*s1==*s2)
            {
                *buf=*s1;
                s1++;
                s2++;
                buf++;
            }
            *buf='\0';
            return s1-p;
        }
        void Test()
        {
            char str1[]="abccade";
            char str2[]="dgcadde";
            int len1=strlen(str1);
            int len2=strlen(str2);
            int i,j,k;
            char **pf1=new char*[len1];
            char **pf2=new char*[len2];
            

            for(i=0;i<len1;i++)
            {
                pf1[i]=&str1[i];
            }
            for(i=0;i<len2;i++)
                pf2[i]=&str2[i];
            qsort(pf1,len1,sizeof(char*),com); // 对后缀数组采用快速排序
            qsort(pf2,len2,sizeof(char*),com);
            k=i=j=0;
            int max=0;
            char *maxbuf=new char[100];
            char *buf=new char[100];
            while(i<len1&&j<len2)
            {
                int t=get(pf1[i],pf2[j],buf);// 比较两个字符串,返回公共长度,并返回相同部分的字符串
                if(t>max)
                {
                    max=t;
                    strcpy(maxbuf,buf);
                }
                if(strcmp(pf1[i],pf2[j])<=0) // 比较两个字符串的大小
                {
                    i++;
                }
                else
                    j++;
            }
            cout<<maxbuf<<endl; 
        }
    };

};

 

转载于:https://www.cnblogs.com/dyc0113/p/3293532.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值