Substrings

题目描述:

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值