第四届河南省ACM-最长公共子串,第四届河南省acm-
第四届河南省ACM-最长公共子串,第四届河南省acm-
第四届河南省ACM
SUBSTRING
Youare given a string input. You are to find the longest substring of input suchthat the reversal of the substring is also a substring of input. In case of atie, return the string that occurs earliest in input.
Note well: Thesubstring and its reversal may overlap partially or completely. The entireoriginal string is itself a valid substring . The best we can do is find a onecharacter substring, so we implement the tie-breaker rule of taking theearliest one first.
【Standardinput】
Thefirst line of input gives a single integer, 1 ≤ N ≤ 10, the number of testcases. Then follow, for each test case, a line containing between 1 and 50characters, inclusive. Each character of input will be an uppercase letter('A'-'Z').
【Standardoutput】
Outputfor each test case the longest substring of input such that the reversal of thesubstring is also a substring of input
【SampleInput】
3
ABCABA
XYZ
XCVCX
【SampleOutput】
ABA
X
XCVCX
My code(没经过测试):
#include<stdio.h>
#include<string.h>
char s1[55],s2[55];
int inf[55][55];
int ss[55];
int len;
int fun(int p)//从s1的P位置开始与s2的最长匹配
{
int j,jj,pp,l,tl;
l=1;
for(j=0;j<len;j++)
{
pp=p;jj=j;tl=0;
while(inf[pp][jj]&&pp<len&&jj<len)
{
pp++;
jj++;
tl++;
}
if(tl>l)l=tl;
}
return l;
}
int main()
{
int i,j,t,line;
scanf("%d",&line);
getchar();
while(line--)
{
gets(s1);
len=strlen(s1);
for(i=0;i<len;i++)s2[i]=s1[len-i-1];
s2[i]='\0';
for(i=0;i<len;i++)
for(j=0;j<len;j++)if(s1[i]==s2[j])inf[i][j]=1;
else inf[i][j]=0;
for(i=0;i<len;i++)
{
ss[i]=fun(i);
}
t=0;
for(i=1;i<len;i++)if(ss[t]<ss[i])t=i;
for(i=t;i<ss[t]+t;i++)printf("%c",s1[i]);
printf("\n");
}
return 0;
}
新思路:如果按照按照一般方法判定两个不相干的字符串的公共子串,肯定好。可是可能会超时,之所以给你反转的例子就是让你找规律的。可以取数组s[n],其中s[x]就是以原字符串数据下标为x的字符为中心其对称的元素的个数则,这样的一个对称串一定是公共串,则max(s[x])(0<=x<n)就是所求结果了。
至于两个不相干的字符串的公共子串求解,还要继续学习。
相关文章
- 暂无相关文章
用户点评