hdu 1238 Substrings(暴力+string类方法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wwwlps/article/details/81738768

题意:求n个字符串的最长公共子串的长度,注意,公共子串翻转后也算同一公共子串

题解:字符串长度<=100,n<=100,t<=10,可以用暴力枚举,一开始我用map去记录每一个字符串的所有子串,最后比较一下最大值

发现超时了,后来才知道,可以以最小长度的那个字符串来枚举所有字符串

详见代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include <vector>
#include<queue>
#include <stack>
#include <map>
#define maxn 1005
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
int n;
string s[105];
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    int mini,minz,maxi;
    while(t--)
    {
       cin>>n;
       minz=200;
       for(int i=0;i<n;i++)
       {
          cin>>s[i];
          if(minz>s[i].size())
          {
             minz=s[i].size();
             mini=i;
          }
       }
       maxi=0;
       for(int i=0;i<s[mini].size();i++)//以最小长度字符串来枚举所有字符串
       {
          for(int j=1;j<=s[mini].size()-i;j++)//其中,最小长度字符串中的子串长度从1递增
          {
             string s1=s[mini].substr(i,j);
             string s2=s1;
             reverse(s2.begin(),s2.end());
             int flag=0;
             for(int u=0;u<n;u++)
             {//如果所有字符串中都没有出现这个子串,则跳出去枚举下一个子串
                if(s[u].find(s1,0)==string::npos&&s[u].find(s2,0)==string::npos)
                {//表示从s[u]中的0位置开始去查找s1,看是否查找成功
                   flag=1;
                   break;
                }
             }
             if(flag==0&&j>maxi)//更新最大值
             {
                maxi=j;
             }
          }
       }
       cout << maxi << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/wwwlps/article/details/81738768