hdu 1238 Substring 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1238
background knowledge:“串”(string)和“序列”(sequence)是完全不同的两个概念,在讨论子串和子序列时,串是连续的,而序列可以不连续,只要有序即可。
题目大意:找多个字符串的最长公共子串(还是LCS,不过这个LCS的S变成了SubString),输出长度。
题目分析:暴力+STL。
code:
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
int cmp(string s1,string s2)
{
return s1.size()<s2.size();
}
int main()
{
int t,n,i,j,k,sum,flagf;
bool flag=true;
string c[110],s;
cin>>t;
while(t--)
{
cin>>n;
for(flagf=sum=i=0;i<n;i++)
{
cin>>c[i];
}
sort(c,c+n,cmp);
for(flag=true,i=1;i<=c[0].size()&&flag;i++)
{
//cout<<"最短串的子串长度跨度是:"<<i<<endl;
for(flag=false,k=0;k+i<=c[0].size()&&!flag;k++)//子串起点
{
s=c[0].substr(k,i);
//cout<<"截出的子串是:"<<s<<endl;
for(j=1;j<n;j++)
{
//cout<<"正在与第"<<j<<"个串匹配"<<endl;
string::size_type idx1=c[j].find(s);
reverse(s.begin(),s.end());
string::size_type idx2=c[j].find(s);
if(idx1==string::npos&&idx2==idx1)break;
}
if(j==n)sum=i,flag=true;
}
}
//string v="abfr";
//printf("%d %s\n",sum,v.find("afr")==string::npos?"false":"true");
cout<<sum<<endl;
}
return 0;
}PS:又自觉复习了String和algorithm的有关内容,大爱STL。
本文介绍了解决HDU 1238问题的方法,该问题是寻找多个字符串间的最长公共子串,并输出其长度。通过使用C++编程语言结合STL标准模板库实现解决方案。
169

被折叠的 条评论
为什么被折叠?



