码迷,mamicode.com
首页 > 其他好文 > 详细

DS串应用—最长重复子串

时间:2020-01-11 20:21:20      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:描述   EDA   次数   new   main   cab   end   namespace   输出   

题目描述

求串的最长重复子串长度(子串不重叠)。例如:abcaefabcabc的最长重复子串是串abca,长度为4。

 

输入

测试次数t

 

t个测试串

 

输出

对每个测试串,输出最长重复子串长度,若没有重复子串,输出-1.

 

样例输入

3 abcaefabcabc szu0123szu szuabcefg

样例输出

4 3 -1

提示

#include<iostream>
#include<string>
using namespace std;
int *getnext(string p)
{
    int j=0,k=-1;
    int *next=new int[p.size()];
    next[0]=-1;
    while(j<(int)p.size()-1)
    {
        if(k==-1||p[j]==p[k])
        {
            j++;
            k++;
            next[j]=k;
        }
        else
            k=next[k];
    }
    return next;
}
 
int KMP(string s,string p)
{
    int i=0,j=0;
    int *next=getnext(p);
    while(i<(int)s.size()&&j<(int)p.size())
    {
        if(j==-1||s[i]==p[j])
        {
            i++;
            j++;
        }
        else
            j=next[j];
    }
    if(j==(int)p.size())
        return i-j+1;
    return -1;
}
int Find(string s)
{
    int L=s.size();
    int Max=-1;
    for(int i=0;i<L;i++)
    {
        for(int j=i;j<L;j++)
        {
            string p=s.substr(i,j-1);
            string save=s;
            int firstindex=KMP(s,p);
            int slength=s.size();
            int plength=p.size();
            string S=s.substr(0,firstindex-1);
            string after=s.substr(firstindex-1+plength,slength);
            S+=after;
            if(KMP(S,p)!=-1)
            {
                int t=plength;
                if(t>Max)
                    Max=t;
            }
            s=save;
        }
    }
    if(Max==0)
        return -1;
    return Max;
}
 
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        string s;
        cin>>s;
        cout<<Find(s)<<endl;
    }
    return 0;
}

DS串应用—最长重复子串

标签:描述   EDA   次数   new   main   cab   end   namespace   输出   

原文地址:https://www.cnblogs.com/SZU-DS-wys/p/12180756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!