Substrings

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12706    Accepted Submission(s): 6115

 

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

题目链接:​​http://acm.hdu.edu.cn/showproblem.php?pid=1238​

 

思路

这个题做了好长时间,提交了四五次,都是错误的。

关键问题是思路跑偏了,第一次做的时候是每次都从0或者从尾部开始截取,没有考虑到中间的子串。当时我还很纳闷WA哪了。后来仔细看看我的代码,发现漏掉了中间子串的情况。

先找到长度最小的字符串,然后用该串的子串和目标字符串进行匹配,看它是不是目标字符串的子串。

有两个重要的点:

① 找长度最小的字符串,用它去构造子串。

② 注意题目中的inverse 即也需要将子串反转然后进行匹配。

这题数据量不大,可以大胆的做。

 

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int MAXN = 100 + 10;
char a[MAXN][MAXN],b[MAXN],c[MAXN];

int main(){
int t;
scanf("%d", &t);
while(t--){
int n,f=0;
scanf("%d", &n);
memset(a, 0, sizeof(a));

int min = 10000;
int m = 0;

for (int i = 0; i < n; i++){
scanf("%s", a[i]);
int t = strlen(a[i]);
if (min > t) {
min = t;
m = i;
}
}

int max = 0;
// 前两个for循环中的i,j为每次构造子串的首和尾下标。
// 第三个for循环 构造字串 赋值。(两个字符数组,一个正序,一个倒序)
for (int i=0; i < min; i++) {
for (int j = i; j < min; j++) {
for(int k = i; k <= j; k++) {
b[k-i] = a[m][k];
c[j-k] = a[m][k];
}
// 构造字符串需要加上`\0`
b[j-i+1] = '\0';
c[j-i+1] = '\0';

bool flag = true;

for (int p = 0; p < n; p++) {
// 判断上边构造的字符串是不是其他字符串的子串
if(p != m && !strstr(a[p], b) && !strstr(a[p], c)){
flag = false;
break;
}
}
// 取较长的子串
if (strlen(b) > max && flag) {
max = strlen(b);
}
}
}
printf("%d\n",max);
}
return 0;
}