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

    // 编程实现:找出两个字符串中最大公共子字符串,如"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; 
        }
    };

};

 

posted on 2013-08-31 21:33  dyc0113  阅读(425)  评论(0编辑  收藏  举报

导航