1. 程式人生 > >最長公共子串(1)--hdu1238(多個字串得最長公共子串--暴力)

最長公共子串(1)--hdu1238(多個字串得最長公共子串--暴力)

Substrings                                                 Time Limit:1000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u

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

       這道題題意:給你n個字串,然後要求求一個最大的子串(或者子串的反串,子串可以倒過來的意思)在每個字串中都出現。要求求這個子串的長度。 

        由於最多十組樣例,並且字串個數最多100,每個字串長度最多100,所以可以直接暴力列舉。為了節省時間,先找出這些串中長度最短的,然後列舉這個串中的所有子串。再讓這個子串或者反串去匹配每一個串,若都符合,即輸出,然後退出。這裡列舉,當然是從子串長度大的往小的列舉啦,節省時間。 不過還是寫了3重for迴圈,但是串的長度,還有串的數量都是100以內的。所以複雜度還可以接受。1000000. 程式碼:

#include<stdio.h>
#include<string.h>
char str[105][105];
char s1[105];
char s2[105];
int main()
{
	int T,n,i,j,k;
	scanf("%d",&T);
	while(T--){
		scanf("%d",&n);
		int min=0;
		for(i=0;i<n;i++){
			scanf("%s",str[i]);
			if(strlen(str[i])<strlen(str[min]))
				min=i;
		}
		int flag=1;
		int MAX=0;
		for(i=0;i<strlen(str[min]);i++){        //i代表列舉的字串的開頭下標
			for(j=i;j<strlen(str[min]);j++){      //j代表列舉的字串的結尾下標
				for(k=i;k<=j;k++){
					s1[k-i]=str[min][k];
					s2[j-k]=str[min][k];
				}
				s1[j-i+1]='\0';
				s2[j-i+1]='\0';
				int l=strlen(s1);
				for(k = 0;k<n;k++)//列舉所有串  
                {  
                    if(!strstr(str[k],s1) && !strstr(str[k],s2))  //字串匹配函式strstr
                    {  
                        flag = 0;  
                        break;  
                    }  
                }  
                if(l>MAX && flag)  
					MAX = l;
				flag = 1;
			}
		}
		printf("%d\n",MAX);
	}
	return 0;
}