题目的意思是,找到各个串的最长子串,输出长度。
我们找到最短的串,枚举这个串的所有子串,需要注意的是,这些子串的逆序也是可以的。
知道了这些,就可以写出代码了。
下面是AC的代码:
#include <iostream>
#include <cstring>
using namespace std;
char str[105][105];
int main()
{
char s1[105], s2[105];
int t, n, i, j, k, f;
cin >> t;
while(t--)
{
cin >> n;
int leng = 2000;
f = -1;
for(i = 0; i < n; i++) // 输入并找到最短的串
{
cin >> str[i];
int len = strlen(str[i]);
if(leng > len)
{
leng = len;
f = i;
}
}
int ans = 0;
int flag = 1;
int length = strlen(str[f]);
for(i = 0; i < length; i++) //枚举最短的串的子串
{
for(j = i; j < length; j++)
{
for(k = i; k <= j; k++) //正序和逆序分别保存在s1和s2
{
s1[k - i] = str[f][k];
s2[j - k] = str[f][k];
}
s1[j - i + 1] = s2[j - i + 1] = '\0';
int l = strlen(s1);
for(int a = 0; a < n; a++) //枚举其他字符串,判断是否存在相同子串
{
if(!strstr(str[a], s1) && !strstr(str[a], s2))
{
flag = 0;
break;
}
}
if(ans < l && flag) //找到最长的子串
{
ans = l;
}
flag = 1;
}
}
cout << ans << endl;
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/qq_25425023/article/details/46975453