南阳理工:Substring,南阳理工substring
分享于 点击 29374 次 点评:266
南阳理工:Substring,南阳理工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
注意:本题意是让求原子符串中某个子串s,如果他的翻转串仍然是原串的子串,并且s是所有子串中最长的,则输出s,而不是求最长对称子串!!!
#include<stdio.h>//求最长对称子串的代码,但是和题意不符合
#include<string.h>
int main()
{
int N,n,i,j,i0,j0,flag,i2,j2,max;
char str[60];
scanf("%d",&N);
while(N--)
{
memset(str,0,sizeof(str));
scanf("%s",str);
n=strlen(str);
i2=j2=0;
for(i=0,max=0;i<n;i++)
{
for(j=i;j<n;j++)
{
for(i0=i,j0=j,flag=1;i0<=j0;i0++,j0--)
if(str[i0]==str[j0]) continue;
else
{
flag=0;
break;
}
if(flag==1&&j-i>max)
{
max=j-i;
i2=i;
j2=j;
}
}
}
for(i=i2;i<=j2;i++)
printf("%c",str[i]);
printf("\n");
}
return 0;
}
#include<stdio.h>//正确代码
#include<string.h>
int panduan(char str1[60],char str2[60])
{
int i=0,j=0,flag=0,n1,n2;
n1=strlen(str1);
n2=strlen(str2);
while(i<n1&&j<n2)
if(str1[i]==str2[j])
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
if(j==n2) flag=1;
return flag;
}
int main()
{
int N,n,i,j,k,i0,len,max;
char str[60],s[60],zc[60];
scanf("%d",&N);
while(N--)
{
memset(str,0,sizeof(str));
memset(s,0,sizeof(s));
scanf("%s",str);
n=strlen(str);
zc[0]=str[0];
zc[1]='\0';
max=1;
for(i=0;i<n;i++)
for(j=i;j<n;j++)
{
for(i0=j,k=0;i0>=i;i0--)
s[k++]=str[i0];
s[k]='\0';
len=strlen(s);
if(len>max)
{
k=panduan(str,s);
if(k==1)
{
strcpy(zc,s);
max=len;
}
}
}
for(i=max-1;i>=0;i--)
printf("%c",zc[i]);
printf("\n");
}
return 0;
}
相关文章
- 暂无相关文章
用户点评