第四届河南省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)//s1P位置开始与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)就是所求结果了。

       至于两个不相干的字符串的公共子串求解,还要继续学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值