子串

子串

(File IO): input:sub.in output:sub.out

Time Limits: 1000 ms Memory Limits: 524288 KB

Description
Description
Input
Input
Output
Output
Sample Input

4
5
ab
abc
zabc
abcd
zabcd
4
you
lovinyou
aboutlovinyou
allaboutlovinyou
5
de
def
abcd
abcde
abcdef
3
a
ba
ccc

Sample Output

4
-1
4
3

Data Constraint
Data


解题思路


此题一看就是KMP

对于你要判断i的字符串是否符合要求,对于前面的j,k,(i > j > k)k串是j串的子串:

  1. 如果k串是i串的子串,j串不一定是i串的子串
  2. 如果k串不是i串的子串,那么j串必定不是i串的子串

也就是说,当我们确定了x串是y串的子串(x < y),判断后面的串是否符合要求就无需再用x串判断了

现在我们用i串去判断当前答案后面的串j,如果i串是j串的子串,那么就可以停止搜索,否则就更新答案继续搜索。O(TNL),L为串长。

#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct juro{
    char st[2010];
    int len;
}str[510];

int t,n,p[510][2010];
int main()
{
    freopen("sub.in","r",stdin);
    freopen("sub.out","w",stdout);
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            char ch=' ';
            str[i].len=0;
            for(;ch < 'a' || ch > 'z';ch=getchar());
            for(;ch >= 'a' && ch <= 'z';ch=getchar())str[i].st[++str[i].len]=ch;
            p[i][1]=0;
            int y=0;
            for(int x=2;x<=str[i].len;x++)
            {
                while(y && str[i].st[x]!=str[i].st[y+1])y=p[i][y];
                if(str[i].st[x]==str[i].st[y+1])y++;
                p[i][x]=y;
            }
        }
        int ans=-1;
        for(int i=1;i<n;i++)
        {
            int s=max(i+1,ans+1);
            for(int j=s;j<=n;j++)
            {
                int x=0;
                bool q=0;
                for(int y=1;y<=str[j].len;y++)
                {
                    while(x && str[i].st[x+1]!=str[j].st[y])x=p[i][x];
                    if(str[i].st[x+1]==str[j].st[y])x++;
                    if(x==str[i].len)
                    {
                        q=1;
                        break;
                    }
                }
                if(q)break;
                ans=max(ans,j);
            }
            if(ans==n)break;
        }
        printf("%d\n",ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值