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 |
题目大意:求最长公共子串,正反都可以,可以直接暴力来求;
需要用到一些字符串函数,在代码中给出解释
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N=105;
int len[N];
char s[N][N];
char s1[N],s2[N];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int j,i,n,mini=inf,u;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",s[i]);
len[i]=strlen(s[i]);
if(len[i]<mini)//记录最短的主串,
{ //从最短的主串中的每个字串找
mini=len[i];
u=i;
}
}
int l,maxx=0,k,g;
for(i=0;i<mini;i++)
{
for(j=1;j<=mini-i;j++)
{
strncpy(s1,s[u]+i,j);//strncpy(s1,s[u]+i,j),作用是
s1[j]='\0'; //复制s[u]从i开始以后的j个字符到s1中
l=strlen(s1);
for(k=l-1,g=0;k>=0;k--)
s2[g++]=s1[k];
s2[l]='\0';
int flag=1;
for(k=0;k<n;k++)
{
if(!strstr(s[k],s1)&&!strstr(s[k],s2))
{//strstr(s,s1);作用是判断s中是否出现s1,出现返回true,没有返回false;
flag=0;
break;
}
}
if(flag==1)
maxx=max(maxx,l);
}
}
printf("%d\n",maxx);
}
return 0;
}