Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9695 Accepted Submission(s): 4602
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
暴力枚举:时间复杂度o(10^6)。
import java.util.Arrays; import java.util.Scanner; import java.util.Comparator; class Comp implements Comparator<String>{ public int compare(String s1,String s2) { return s1.length()-s2.length(); } } public class Main{ static Scanner cin=new Scanner(System.in); static final int MAXN=105; static int n; static String[] s = new String[MAXN]; static String reverse(String s) { String rev=""; int len=s.length(); for(int i=0;i<len;i++) { rev=s.charAt(i)+rev; } return rev; } public static void main(String[] args){ int T=cin.nextInt(); while(T--!=0) { int n; n=cin.nextInt(); for(int i=0;i<n;i++) { s[i]=cin.next(); } Arrays.sort(s,0,n,new Comp()); int len=s[0].length(); label: while(len>0) { String ss; String rs; int s0len=s[0].length(); for(int start=0;start+len<=s0len;start++) { ss=s[0].substring(start, start+len); rs=reverse(ss); int mark=0; for(int j=1;j<n;j++) { if(s[j].indexOf(ss)!=-1||s[j].indexOf(rs)!=-1) { mark++; } } if(mark==n-1) { break label; } } len--; } System.out.println(len); } } }