写这道题时,是为了熟悉一下KMP算法……花了一整天找错。辛苦啊!
这是自己写的KMP算法
#include<iostream>
#include<cstring>
using namespace std;
#define N 100
#define L 100
char s[N+10][L+10];
int next[N+10];
void getNext(char *s)
{
int len = strlen(s);
int i,k;
i = 0, k = -1;
next[0] = -1;
char ch = s[0];
while(i<len - 1)
{
if(k == -1 || ch == s[i]) k ++, next[++i] = k;
else k = next[k];
if(k != -1) ch = s[k];
}
}
int f(char *s, char *obj)
{
getNext(obj);
int i,j,k;
i = 0, j = 0;
while(s[i] != '\0')
{
if(j == -1) i++, j++;
else if(obj[j] == '\0')
{
return 1;
}
else if(s[i] == obj[j]) i++, j++;
else if(s[i] != obj[j]) j = next[j];
}
if(obj[j] == '\0') return 1;
return 0;
}
int main()
{
int i,j,k;
int cases;
scanf("%d", &cases);
while(cases --)
{
int n;
scanf("%d\n", &n);
for(i=0; i<n; i++)
{
scanf("%s", &s[i]);
//printf("%s\n", s[i]);
}
int len = strlen(s[0]);
int res = 0;
for(i=1; i<=len; i++)
for(j=0; j+i-1<len; j++)
{
bool isOK = true;
char a[N+10], b[N+10];
for(k=0; k<i; k++)
a[k] = s[0][j+k];
a[i] = '\0';
for(k=0; k<i; k++)
b[k] = s[0][j+i-1-k];
b[i] = '\0';
for(k=1; k<n && isOK == true; k++)
{
if(f(s[k], a) == 0 && f(s[k], b) == 0) isOK = false;
}
if(isOK == true) res = i;
}
printf("%d\n", res);
}
return 0;
}
后来经人点醒,才想起原来C类库中有个字符匹配算法。。呃。。
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
#define N 100
#define L 100
char s[N+10][L+10];
int main()
{
int i,j,k;
int cases;
scanf("%d", &cases);
while(cases --)
{
int n;
scanf("%d\n", &n);
for(i=0; i<n; i++)
scanf("%s", &s[i]);
int len = strlen(s[0]);
int res = 0;
for(i=1; i<=len; i++)
for(j=0; j+i-1<len; j++)
{
bool isOK = true;
char a[N+10], b[N+10];
for(k=0; k<i; k++)
a[k] = s[0][j+k];
a[i] = '\0';
for(k=0; k<i; k++)
b[k] = s[0][j+i-1-k];
b[i] = '\0';
for(k=1; k<n && isOK == true; k++)
{
if(strstr(s[k], a) == NULL && strstr(s[k], b) == NULL) isOK = false;
}
if(isOK == true) res = i;
}
printf("%d\n", res);
}
return 0;
}