Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11914 Accepted Submission(s): 5708
Problem Description
You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.
Input
The first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.
Output
There should be one line per test case containing the length of the largest string found.
Sample Input
2 3 ABCD BCDFF BRCD 2 rose orchid
Sample Output
2 2
Author
Asia 2002, Tehran (Iran), Preliminary
Recommend
Eddy | We have carefully selected several similar problems for you: 1010 1239 1240 1016 1242
跟我上一篇博客异曲同工之妙
只要用strncpy 加两次kmp就可以判断
#include <cstdio>
#include <cstring>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
#include <set>
using namespace std;
#define dbg(x) cout<<#x<<" = "<< (x)<< endl
const int MAX_N = 65;
char str[15][MAX_N];
int Next[MAX_N],n,len;
int kmp(const char *T,const char *P){
int t = -1,j = 0;
Next[0] = -1;
int lenT = strlen(T),lenP= strlen(P);
while(j<lenP-1){
if(t<0||P[t]==P[j]) {++t,++j,Next[j]=(P[j]==P[t]?Next[t]:t);}
else t = Next[t];
}
int i = 0;
j = 0;
while(i<lenT&&j<lenP){
if(j<0||T[i]==P[j]) i++,j++;
else j = Next[j];
}
return j==lenP;
}
bool match(const char *Substr){
char Substr_[124];
int len = strlen(Substr);
for(int i=0;i<len;i++) Substr_[i] = Substr[len-1-i];
Substr_[len] = '\0';
//dbg(Substr_);
for(int i = 1;i<n;++i) if(!kmp(str[i],Substr)&&!kmp(str[i],Substr_)) return false;
return true;
}
int main(){
int t ;
scanf("%d",&t);
char ans[MAX_N],tmp[MAX_N];
while(t--){
memset(ans,0,sizeof(ans));
scanf("%d\n",&n);
for(int i=0;i<n;i++){
scanf("%s",str[i]);
}
int flag = 0;
int len_start = strlen(str[0]);
for(len = len_start;len>0;--len){
for(int pos = 0;pos<=len_start-len;pos++){
strncpy(tmp,str[0]+pos,len);
tmp[len] = '\0';
//dbg(tmp);
if(match(tmp) ) {
int lenT=strlen(tmp);
int lenA = strlen(ans);
if(lenT>lenA)
strcpy(ans,tmp);
flag = 1;
}
}
if(flag) break;
}
//dbg(ans);
int len_ans = strlen(ans);
printf("%d\n",len_ans);
}
return 0;
}