【PAT】1040. Longest Symmetric String (25)

题目描述:

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given “Is PAT&TAP symmetric?”, the longest symmetric sub-string is “s PAT&TAP s”, hence you must output 11.

翻译:给你一个字符串你需要输出最长的对称字串长度。例如,给你”Is PAT&TAP symmetric?”, 最长的对称子串是 “s PAT&TAP s”, 所以你需要输出11。

INPUT FORMAT

Each input file contains one test case which gives a non-empty string of length no more than 1000.

翻译:每个输入文件包含一组测试数据,每组测试数据包含一个长度不超过1000的非空字符串。

OUTPUT FORMAT

For each test case, simply print the maximum length in a line.

翻译:对于每组输入数据,输出一行最长的长度。


Sample Input:

Is PAT&TAP symmetric?

Sample Output:

11


解题思路

遍历每个字符,比较左边的和右边的字符是否一致,如果不一致或越界则退出。注意还要比较两个字符的情况。复杂度最高为O(2*1000^2),还是

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;

int main(){
    string s;
    getline(cin,s);
    int Max=0; 
    int length=s.size();
    for(int i=0;i<length;i++){//搜索*a*格式 
        int temp=1;
        for(int j=1;;j++){
            if(i-j<0||i+j>=length)break;
            if(s[i-j]!=s[i+j])break;
            temp+=2;
        }
        Max=max(Max,temp);
    }
    for(int i=0;i<length;i++){//搜索*aa*格式 
        int temp=0;
        for(int j=0;;j++){
            if(i-j<0||i+j+1>=length)break;
            if(s[i-j]!=s[i+1+j])break;
            temp+=2;
        }
        Max=max(Max,temp);
    }
    printf("%d\n",Max);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值