第四屆河南省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)就是所求結果了。

       至於兩個不相干的字符串的公共子串求解,還要繼續學習。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章