hdu1238 Substrings

Substrings

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


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  1242  1241 
 
 
题意就是给你n串字符串,求出这些字符串中公共最大的子串(正反都行)
思路:找到最小的母串(最大子串肯定在最小的母串中),然后枚举,如果全部匹配,则记录下来,最后得到最大的
/*状态AC*/
import java.util.Scanner;

public class hdu1238_Substrings {
	static String[] str = new String[105];

	public static void main(String[] args) {
		Scanner sc =new Scanner (System.in);
		int tcase = sc.nextInt();
		while(tcase-->0){
			int  Min=1000,k=0;
			int n =sc.nextInt();
			/*找到最小串*/
			for(int i=0;i<n;i++){
				str[i] = sc.next();
				if(str[i].length()<Min) {
					Min = str[i].length();
					k = i;
				}
			}
			int Max = 0;
			String str1,str2;//子串以及反子串
			boolean flag = true; //是否出现过
			for(int i=0;i<str[k].length();i++){//枚举子串的头
				for(int j=i;j<str[k].length();j++){//子串的尾
					str1 = str[k].substring(i,j+1);
					str2 = reverse(str1);
					//System.out.println(str1+str2);
					int len = str1.length();
					/*枚举所有串*/
					for(int t=0;t<n;t++){
						 
						if(str[t].indexOf(str1)==-1&&str[t].indexOf(str2)==-1) {//当正反子串在母串中都未发现时即跳出
							flag = false;
							break;
						}
					}
					if(flag&&len>Max) Max = len; 
					flag = true;
				}
			}
			System.out.println(Max);
		}
	}
    

	public static String reverse(String s) {
		char ch[] = s.toCharArray();
		int start = 0, end = ch.length - 1;
		char temp;
		while (start < end) {
			temp = ch[start];
			ch[start] = ch[end];
			ch[end] = temp;
			start++;
			end--;
		}
		String s1 = String.copyValueOf(ch);
		return s1;
	}
}

  

你可能感兴趣的:(hdu1238 Substrings)