nyoj 308 Substring

Substring

時間限制:1000 ms  |  內存限制:65535 KB
難度:1
描述

You are given a string input. You are to find the longest substring of input such that the reversal of the substring is also a substring of input. In case of a tie, return the string that occurs earliest in input. 

Note well: The substring and its reversal may overlap partially or completely. The entire original string is itself a valid substring . The best we can do is find a one character substring, so we implement the tie-breaker rule of taking the earliest one first.

輸入
The first line of input gives a single integer, 1 ≤ N ≤ 10, the number of test cases. Then follow, for each test case, a line containing between 1 and 50 characters, inclusive. Each character of input will be an uppercase letter ('A'-'Z').
輸出
Output for each test case the longest substring of input such that the reversal of the substring is also a substring of input
樣例輸入
3                   
ABCABA
XYZ
XCVCX
樣例輸出
ABA
X
XCVCX
剛開始做的時候,英語沒有理解清楚,做成求最長迴文串了,wa了一次
又讀了一下題目意思,以後還是認真仔細點吧
題目意思:
在給出的字符串中找到一個最長子串,條件是其子串的逆串也出現在字符串中

因爲字符串最長爲50,直接暴力

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

char s1[55];
char s2[55];
char s3[55];
char s4[55];

int main(){
    int i,j,k,t,n,Max,len,l;
    scanf("%d",&t);
    while(t--){
        Max=-1;
        memset(s1,0,sizeof(s1));
        memset(s2,0,sizeof(s2));
        scanf("%s",s1);
        len=strlen(s1);
        for(i=0,j=len-1;i<len;i++,j--)
            s2[j]=s1[i];
        if(!strcmp(s1,s2)){
            printf("%s\n",s1);
            continue;
        }
        Max=-1;
        for(i=0;i<len;i++){
            for(j=1;j<=len;j++){
                l=0;
                memset(s3,0,sizeof(s3));
                for(k=i;k<j;k++){
                    s3[l++]=s1[k];
                }
                if(strstr(s2,s3)&&l>Max){
                    Max=l;
                    strcpy(s4,s3);
                }
            }
        }
        printf("%s\n",s4);
    }
    return 0;
}


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