Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 7659 Accepted Submission(s): 3447
Problem 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 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.
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
Asia 2002, Tehran (Iran), Preliminary
Recommend
题意:
题目大概意思是给出一系列的字符串,找到最大的相同连续字符。
现将字符串按短到长排序,然后枚举最短的字符串的子串,依次和其他的进行比较,找出其最大的子串即可。其中,用到了strstr函数。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct chuan{
char num[110];
}a[110];
bool cmp(chuan b,chuan c)
{
return strlen(b.num)<strlen(c.num);
}
int main()
{
int i,j,n,t;
int len,l;
int get;
int k1,k2,k;
int p1,p2;
char s[300];
char m[300];
int max=0;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%s",&a[i].num);
sort(a+1,a+n+1,cmp);
l=strlen(a[1].num);
max=0;
for(i=0;i<l;i++)
{
for(j=i;j<l;j++)
{
p1=p2=0;
for(k1=i,k2=j;k1<=j,k2>=i;k1++,k2--)
{
s[p1++]=a[1].num[k1];
m[p2++]=a[1].num[k2];
}
s[p1]='\0';
m[p2]='\0';
len=p1;
get=1;
for(k=2;k<=n;k++)
{
if(strstr(a[k].num,s)!=NULL||strstr(a[k].num,m)!=NULL)
continue;
else
{
get=0;
break;
}
}
if(get!=0&&len>max)
max=len;
}
}
printf("%d\n",max);
}
// while(1);
return 0;
}
#include<string.h>
#include<algorithm>
using namespace std;
struct chuan{
char num[110];
}a[110];
bool cmp(chuan b,chuan c)
{
return strlen(b.num)<strlen(c.num);
}
int main()
{
int i,j,n,t;
int len,l;
int get;
int k1,k2,k;
int p1,p2;
char s[300];
char m[300];
int max=0;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%s",&a[i].num);
sort(a+1,a+n+1,cmp);
l=strlen(a[1].num);
max=0;
for(i=0;i<l;i++)
{
for(j=i;j<l;j++)
{
p1=p2=0;
for(k1=i,k2=j;k1<=j,k2>=i;k1++,k2--)
{
s[p1++]=a[1].num[k1];
m[p2++]=a[1].num[k2];
}
s[p1]='\0';
m[p2]='\0';
len=p1;
get=1;
for(k=2;k<=n;k++)
{
if(strstr(a[k].num,s)!=NULL||strstr(a[k].num,m)!=NULL)
continue;
else
{
get=0;
break;
}
}
if(get!=0&&len>max)
max=len;
}
}
printf("%d\n",max);
}
// while(1);
return 0;
}
先将字符串按长度从短到长排序,枚举最短的字符串的子串,判断是否都是别的字符串的子串,求出最大