题意:找n个串的长度>=3的公共子串
分析:
以第一个串为模板,枚举它的所有子串检查它是否为其他n-1个串
的子串,如果是则筛选长度最大且字典序最小的。
strncpy(s1,s,n) 函数作用是 将s指针所指位置开头的n个字符复制到s1字符串中。
strstr(s1,s2)判断s2是否为s1的子串,如果不是返回NULL,否则先确定s2在s1
的第一次出现的位置,并返回此s2在s1首位置的地址
暴力方法是用strstr来判断模式串是否为后n-1个串的子串。也可以用KMP算法判断。
其实可以不用找第一个串的所有子串,只找长度为3-n的后缀子串。
暴力:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
using namespace std;
typedef long long ll;
char s[12][65],ans[65],t[65];
int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%s",s[i]);
int l = 0;
for(int j=1;j<=60;j++){
for(int st=0;st<60;st++){
strncpy(t,s[1]+st,min(j,60-st+1));
int flag = 0;
for(int k=2;k<=n;k++){
if(strstr(s[k],t)==NULL){
flag=1;
break;
}
}
if(!flag)
{
int len = strlen(t);
if(len>l){
l = len;
strcpy(ans,t);
}
else if(len==l && strcmp(ans,t)>0){
strcpy(ans,t);
}
}
}
}
if(l<3) printf("no significant commonalities\n");
else printf("%s\n",ans);
}
return 0;
}
KMP:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<ctime>
#define eps (1e-8)
using namespace std;
typedef long long ll;
char s[12][65],ans[65],t[65];
int f[65];
void getnext(char *x,int m)
{
f[0]=0,f[1]=0;
for(int i=1;i<m;i++){
int j = f[i];
while(j && x[i]!=x[j]) j=f[j];
f[i+1] = (x[i]==x[j])?j+1:0;
}
}
bool KMP(char *s,char *t)
{
memset(f,0,sizeof(f));
int a = strlen(s);
int b = strlen(t);
getnext(t,b);
int j = 0;
for(int i=0;i<a;i++){
while(j && s[i]!=t[j]) j=f[j];
if(s[i]==t[j]) j++;
if(j==b) return true;
}
return false;
}
int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%s",s[i]);
int l = 0;
for(int j=1;j<=60;j++){
for(int st=0;st<60;st++){
strncpy(t,s[1]+st,min(j,60-st+1));
int flag = 0;
for(int k=2;k<=n;k++){
if(!KMP(s[k],t)){
flag=1;
break;
}
}
if(!flag)
{
int len = strlen(t);
if(len>l){
l = len;
strcpy(ans,t);
}
else if(len==l && strcmp(ans,t)>0){
strcpy(ans,t);
}
}
}
}
if(l<3) printf("no significant commonalities\n");
else printf("%s\n",ans);
}
return 0;
}