DS串應用—最長重復子串


題目描述

求串的最長重復子串長度(子串不重疊)。例如: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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM