L2-008 最长对称子串 (25 分) (模拟)

链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805067704549376


题目:

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:

Is PAT&TAP symmetric?

输出样例:

11

思路:
遍历字符串中的每个位置 在每个位置枚举长度判断此长度能否构成一个回文串 需要对长度的奇偶性分类讨论

代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
string s;

int main(){
    getline(cin,s);
    int len=s.length();
    int ans=0;
    for(int i=0;i<len;i++){
        for(int j=0;i-j>=0 && i+j<len;j++){
            if(s[i-j]!=s[i+j]) break;
            ans=max(ans,j*2+1);
        }
        for(int j=0;i-j>=0 && i+j+1<len;j++){
            if(s[i-j]!=s[i+j+1]) break;
            ans=max(ans,j*2+2);
        }
    }
    printf("%d\n",ans);
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/whdsunny/p/10616061.html