题目描述:
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.
输入:
The first line of the input file 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.
输出:
There should be one line per test case containing the length of the largest string found.
样例输入:
2
3
ABCD
BCDFF
BRCD
2
rose
orchid
样例输出:
2
2
code:
字符串的水题,暴力找到可能的子串,然后KMP判断
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
char a[200][500];
char b[500];
char c[500];
int nextt[500];
int nexxt[500];
void init()
{
int i=0,j=-1;
nextt[0]=-1;
int m=strlen(b);
while(i<m)
{
if(j==-1||b[i]==b[j])
{
i++;
j++;
nextt[i]=j;
}
else
{
j=nextt[j];
}
}
}
void init2()
{
int i=0,j=-1;
nexxt[0]=-1;
int m=strlen(c);
while(i<m)
{
if(j==-1||c[i]==c[j])
{
i++;
j++;
nexxt[i]=j;
}
else
{
j=nexxt[j];
}
}
}
bool kmp(int what)
{
int i=0,j=0;
int flag=0;
init();
int n=strlen(a[what]);
int m=strlen(b);
while(i<n)
{
if(j==-1||a[what][i]==b[j])
{
j++;
i++;
}
else j=nextt[j];
if(j==m)
{
return true;
}
}
return false;
}
bool kmp2(int what)
{
int i=0,j=0;
int flag=0;
init2();
int n=strlen(a[what]);
int m=strlen(c);
while(i<n)
{
if(j==-1||a[what][i]==c[j])
{
j++;
i++;
}
else j=nexxt[j];
if(j==m)
{
return true;
}
}
return false;
}
bool cmp(string a,string b)
{
return a<b;
}
int main()
{
int ttt,n;
scanf("%d",&ttt);
while(ttt--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",a[i]);
}
int m=strlen(a[0]);
int flag=0;
int much;
int sum=0;
for(int i=0;i<=m;i++)
{//减掉几个
for(int j=0;j<=i;j++)
{//该字符串前面减掉几个
int start=j,over=m-i+j-1;//后面减掉几个
memset(b,'\0',sizeof(b));
int qq=0;
for(int k=start;k<=over;k++)
{
b[qq++]=a[0][k];
}
memset(c,'\0',sizeof(c));
qq=0;
for(int k=over;k>=start;k--)
{
c[qq++]=a[0][k];
}
int ji=1;
for(int k=1;k<n;k++)
{
if(kmp(k)==0&&kmp2(k)==0)
{
ji=0;
}
}
if(ji==1)
{
flag=1;
}
if(flag)break;
}
if(flag)break;
}
printf("%d\n",strlen(b));
}
return 0;
}