acm pku 1226 Substring的算法分析与实现

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 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 

Source

Tehran 2002 Preliminary

 

分析:题目的意思是寻找所有给出字符串的公共字串,由于字符串的长度不会大于100 而且最多也就100个字符串,因此可以直接搜索:直接根据某字符串,生成其所有子串,判断子串是否是所有字符串的共有子串,搜索时先搜索长度较长的子串,第一个满足条件的子串长度即为结果。当然这里还可以通过先寻找所有字符串中最短的字符串来产生子串,这样可以稍微加快搜索时间

 

代码实现:

#include <string.h>

#include <stdio.h>

#include "iostream"

using namespace std;

char str[100][101];

char res[101];

 

int SubString(char *Source, int m)

{

       int strLen = strlen(Source);

       char substr[101], resubstr[101];

       int i, j, k;

       bool flag ;

 

       for(i = strLen; i > 0; i--)

       {

              for(j = 0; j <= strLen-i; j++)

              {

                     strncpy(substr, Source+j, i);

                     substr[i] = '/0';

                     strcpy(resubstr, substr);

                     _strrev(resubstr);                

                     flag = true;

                     for(k = 0; k < m; k++)

                     {

                            if(strstr(str[k], substr) == NULL && strstr(str[k], resubstr) == NULL)

                            {

                                   flag = false;

                                   break;

                            }

                     }

                     if(flag)

                            return i;

              }

       }

       return 0;

}

 

int main(void)

{

       int n, m;

       int i;

       cin >> n;

       while(n-- > 0)

       {

              cin >> m;

              for(i = 0; i < m; i++)

                     cin >> str[i];

              cout << SubString(str[0], m) << endl;

       }

       return 0;

}

 

提交结果:

Problem: 1226

 

User: uestcshe

Memory: 236K

 

Time: 16MS

Language: C++

 

Result: Accepted

 

你可能感兴趣的:(acm pku 1226 Substring的算法分析与实现)