思路:先找到所有字符串里最短的那个,并且枚举它所有的子串(包括正负),然后用这些子串和别的字符串比较(有现成的strstr函数)因为数据量不大,不用担心超时问题;
代码如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;
void clear(char (*a)[110])//初始化
{
int i, j;
for (i = 0; i < 110; i++)
for (j = 0; j < 110; j++)
a[i][j] = '\0';
}
int main()
{
int t;
int n;
int i,x,y;
char a[110][110];
char base[110];
int len[110],lenmin,lenpoint;
int head, tail;//子串的头尾
int flag,key;
char temp1[110],temp2[110];
cin >> t;
while (t--)
{
cin >> n;
getchar();
clear(a);
flag = 0;//代表找到后,或者找完了,直接退出循环
key = 1;//代表有没有找到
for (i = 0; i < n; i++)
{
scanf("%s", a[i]);
len[i] = strlen(a[i]);
}
lenmin = len[0];
lenpoint = 0;
for (i = 0; i < n; i++)
{
if (len[i] < lenmin)
{
lenmin = len[i];
lenpoint = i;
}
}
strcpy(base, a[lenpoint]);
for (i = lenmin; i >= 1; i--)//枚举最短字符串的所有子串(从最长子串开始)
{
if (flag)
break;
for (head = 0, tail = head + i; tail <= lenmin; head++,tail++)
{
y = 0;
key = 1;//初始化
flag = 0;
memset(temp1, 0, sizeof(temp1));//对子串初始化
memset(temp2, 0, sizeof(temp2));
for (x = head; x < tail; x++)//得到子串(正)
{
temp1[y++] = base[x];
}
y = 0;
for (x = tail - 1; x >= head; x--)
temp2[y++] = base[x];
temp1[y] = temp2[y] = '\0';
for (x = 0; x < n; x++)
{
if (strstr(a[x], temp1) == NULL && strstr(a[x], temp2) == NULL)
{
key = 0;
break;
}
}
if (key)
{
flag = 1;
cout << strlen(temp1) << endl;
break;
}
}
}
if (!key)
{
cout << "0" << endl;
}
}
system("pause");
return 0;
}