题目描述
题目叭叭说了一大堆,其实意思就是让你在n个字符串中找到一个最长的公共子串,如果长度小于3输出:no significant commonalities
否则输出最长的子串即可。
解题思路
首先将第一个串分解,把其所有的子串作为kmp的模式串,在剩余的字符串中查找,如果剩余的字符串中都存在该模式串,就更新答案(公共子串的长度 和 公共子串)。
最后根据题目要求输出即可。
注意如果在过程中出现同为k的子串,则按字典序小的为准。
如果不了解KMP,可以查看博主的另一篇博文 KMP算法详解【ORZ式教学】
代码部分
#include <iostream>
#include <string>
using namespace std;
const int maxn = 1e4 + 10;
int nex[maxn];
void GetNext(string B)
{
int len_B = B.size();
nex[0] = -1;
int k = -1,j = 0 ;
while(j < len_B)
{
if(k == -1 || B[j] == B[k])
{
++ k; ++ j;
nex[j] = k;
}
else
k = nex[k];
}
}
int kmp(string A, string B) // 判断B串在A串中出现的次数
{
int ans = 0, i = 0, j = 0;
int len_B = B.size(), n = A.size();
while(i<n)
{
if(j==-1||A[i] == B[j])
{
++i;
++j;
}
else
j = nex[j];
if(j == len_B)
{
ans ++;
j = nex[j];
}
}
return ans;
}
int main()
{
int t;
cin >> t;
while(t --)
{
int n;
cin >> n;
string s[15], c, a;
int ans = -1;
for(int i = 0; i < n; ++ i) cin >> s[i];
for(int i = 0; i < (int)s[0].size(); ++ i) //分解子串
{
c = "";
for(int j = i; j < (int)s[0].size(); ++ j)
{
c += s[0][j];
GetNext(c);
bool f = true;
for(int k = 1; k <n; ++ k)
if(kmp(s[k], c) == 0) f = false;
if(f)
{
if(ans < (int)c.size())
{
ans = (int)c.size();
a = c;
}
if(ans == (int)c.size()) //如果长度相等,则输出字典序小的子串
{
a = min(a, c);
}
}
}
}
if(ans < 3)
cout << "no significant commonalities" << endl;
else
cout << a << endl;
}
return 0;
}