Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 7450 Accepted Submission(s): 3361
2 3 ABCD BCDFF BRCD 2 rose orchid
2 2
题目大意:求出n个字符串的最长公共子序列,字符串可反转。
题解:先找出最短的字符串,然后在最短字符串中找子串。
如果子串或子串的反转为所有字符串的子串,将子串长度记录下来。
依此......求得所有子串长度中的最大者,即为最长公共子串。
*/
思考:题目中用到很多C++中处理字符串的函数,使解题变得简单。
#include<cstdio>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
#define inf 110
int main()
{
int T,n,i,j,k,mpos,mlen,max;
string s[110];
scanf("%d",&T);
while(T--)
{
mlen=inf;
max=0;
scanf("%d",&n);
for(i=0; i<n; i++)//找最短的字符串
{
cin>>s[i];
if(mlen>s[i].size())
{
mpos=i;
mlen=s[i].size();
}
}
for(i=mlen; i>=1; i--)//从最短的字符串中找子串
{
for(j=0; j<mlen-i+1; j++)
{
string s1,s2;
s1=s[mpos].substr(j,i);//取最短字符串的子串
s2=s1;
reverse(s2.begin(),s2.end());//将子串反转
for(k=0; k<n; k++)
{
if(s[k].find(s1)==-1&&s[k].find(s2)==-1)
{
break;
}
}
if(k==n&&s1.size()>max)
{
max=s1.size();
}
}
}
printf("%d\n",max);
}
return 0;
}
385




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



