HDOJ 1238:Substrings

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
 


/*   
    Coder: Shawn_Xue   
    Date: 2015.4.4   
    Result: AC   
*/ 
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int t, n;
    cin >> t;
    while(t--)
    {
        cin >> n;
        /*  指针指向分配n个string的空间   */
        string *a = new string[n];  //保存n个string
        string *b = new string[n];  //保存n个string的翻转
        int minIndex;   //记录最小字符串的下标
        int minLength = 150;
        for(int i = 0; i < n; i ++)
        {
            cin >> a[i];
            b[i] = a[i];
            reverse(b[i].begin(), b[i].end());  //翻转
            if(minLength > a[i].length())
            {
                minLength = a[i].length();
                minIndex = i;
            }
        }
        string subString;   //保存每次枚举的字符串
        int maxLength = 0;  //保存子字符串的最长长度
        for(int i = 0; i < minLength; i++)  //最小字符串的起始
            for(int j = 0; j <= minLength-i; j ++)  //最小字符串的结束位置
            {
                subString = a[minIndex].substr(i,j);//截取最小字符串的i位置,长度为j的子字符串
                int k;
                for(k = 0; k < n; k ++) //遍历n个字符串
                {
                    if(a[k].find(subString) == -1 && b[k].find(subString) == -1)  //若有字符串且逆反都不满足,则退出
                        break;
                }
                if(k == n)  //每一个字符串都可以匹配子字符串
                    maxLength = max(maxLength, j);
            }
        /*  释放a指向的n个string空间  */
        delete []a;
        delete []b;
        cout << maxLength << endl;
    }
}




你可能感兴趣的:(HDOJ 1238:Substrings)