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.
2 3 ABCD BCDFF BRCD 2 rose orchid
22
题目大意:
题目的意思就是求最小的字串长度,字串可以是反串,也可以是本身的字串,也就是本身可以不是字串,但是他的反串也可以是他的子串。那么长度依然可以是这样长。
思路就是:找到一个最小的长度,作为一个寻找串,求的他的个个字串,之后就是比较,其他长度的串,可以不要去寻找了,因为找的字串,每个都要有。所以我们只要找一遍就可以了。选择的自然就是最小长度的串。减少时间!
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<string.h> using namespace std; int main() { int n,t; scanf("%d",&n); while(n--) { int m; scanf("%d",&m); string fre[105]; int len = 99999; int o; for(int i=0; i<m; i++) { cin>>fre[i]; if(len>fre[i].length()) { len = fre[i].length(); o=i; } } int max = 0; for(int j=len; j>=1; j--) { for(int k=0; k<=len-j; k++) { //从k位置开始,截取到j长度的位置。 string ans = fre[o].substr(k,j); string ans1 = ans; reverse(ans1.begin(),ans1.end()); for( t=0;t<m;t++) { if(fre[t].find(ans1)==-1 && fre[t].find(ans)==-1) { break; } } if(t==m) { if(max<ans1.length()) { max = ans1.length(); break; } } } } printf("%d\n",max); } return 0; }