最长对称子串

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

输入格式:

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

输出格式:

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

输入样例:

Is PAT&TAP symmetric?

输出样例:

11

#include <bits/stdc++.h>
using namespace std;
string str;
int ans;
int len;
int judge(int fore,int back,int slen){
    while(fore >= 0 && back < len){
        if(str[fore] == str[back])
            slen += 2,fore--,back++;
        else break;
    }
    ans = max(ans,slen);
    return ans;
}
int main(){
    //freopen("in","r",stdin);
    ios::sync_with_stdio(0);
    getline(cin,str);
    len = str.size();
    for(int i = 0; i < len; i++){
        //长度为奇数
        judge(i - 1, i + 1,1);
        //长度为偶数
        judge(i,i + 1,0);
    }
    cout << ans;
    return 0;
}
View Code

 

 
posted @ 2020-02-20 09:12  Hazelxcf  阅读(293)  评论(0)    收藏  举报