思考:此题目用暴力即可,不过用点字符串库函数比较方便简洁,strstr,strncopy. 练习估计时间复杂度。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 10+5;
const int maxm = 60+10;
//Accepted 660K 16MS G++ 1498B 2014-04-04 11:53:56
char src[maxn][maxm];
int main()
{
int T;
scanf("%d", &T);
char ans[maxm];
ans[0] = '\0';
while(T--) {
int n;
scanf("%d", &n);
getchar();
for(int i = 0; i < n; i++) {
gets(src[i]);
}
int length = strlen(src[0]);
char now[maxm];
for(int i = 0; i < length; i++ ) {
for(int j = i+2; j < length; j++) {
strncpy(now, src[0]+i, j-i+1);
now[j-i+1] = '\0';
//puts(now);
bool ok = true;
for(int i = 1; i < n; i++) {
char* pos = strstr(src[i], now);
if(pos != NULL) continue;
else {
ok = false;
break;
}
}
if(ok) {
int len1 = strlen(now);
if(len1 > strlen(ans) || (len1 == strlen(ans) && strcmp(now, ans)<0)) {
strcpy(ans, now);
}
}
}
}
int Size = strlen(ans);
if(Size >= 3) puts(ans);
else printf("no significant commonalities\n");
memset(ans, '\0', sizeof(ans)); // WA。
}
return 0;
}