poj1226 Substrings------KMP

Substrings
Time Limit: 1000MSMemory Limit: 10000K
Total Submissions: 9258Accepted: 3177

Description

You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.

Input

The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.

Output

There should be one line per test case containing the length of the largest string found.

Sample Input

2
3
ABCD
BCDFF
BRCD
2
rose
orchid

Sample Output

2
2 

Source

 
题意:求n个字符串的最长公共串,包括反串。
要枚举一个最短的字符串的所有子串。
#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<string.h>
#include<memory.h>
using namespace std;
char ss[110][110];
int fail[110];
int kmp(char *str,char *pat)
{
    int i,j,k;
    memset(fail,-1,sizeof(fail));
    for(i=1;pat[i];i++)
    {
        for(k=fail[i-1];k>=0&&pat[i]!=pat[k+1];k=fail[k]) ;
        if(pat[k+1]==pat[i]) fail[i]=k+1;
    }
    i=j=0;
    while(str[i]&&pat[j])
    {
        if(pat[j]==str[i]) ++i,++j;
        else if(j==0) ++i;
        else j=fail[j-1]+1;
    }
    if(pat[j]) return -1;
    else return i-j;
}
int main()
{
    int t,n;
    char yes[110],no[110],sho[110];
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int maxn=110;
        int l,q;
        for(int i=0;i<n;i++)
        {
            scanf("%s",ss[i]);
            l=strlen(ss[i]);
            if(l<maxn)
            {maxn=l;q=i;}
        }
        strcpy(sho,ss[q]);
        l=strlen(ss[q]);
        //cout<<sho<<"&"<<endl;
        bool flag=false;
        while(maxn)
        {
            for(int i=0;i<=l-maxn;i++)
            {
                strncpy(yes,sho+i,maxn);
                yes[maxn]='\0';
                //cout<<yes<<"*"<<endl;
                for(int j=0;j<maxn;j++)
                no[j]=yes[maxn-j-1];
                no[maxn]='\0';
                //cout<<no<<endl;
                int kk;
                for(kk=0;kk<n;kk++)
                {
                    if(!(kmp(ss[kk],yes)>=0||kmp(ss[kk],no)>=0))
                    break;
                }
                if(kk>=n)
                {
                    flag=true;break;
                }
            }
            if(flag)break;
            maxn--;
        }
        printf("%d\n",maxn);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值