pat甲级1040. Longest Symmetric String (25)

原题链接:https://www.patest.cn/contests/pat-a-practise/1040

欢迎访问我的pat甲级题解目录哦https://blog.csdn.net/richenyunqi/article/details/79958195

1040. Longest Symmetric String (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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.

Input Specification:

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

Output Specification:

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

Sample Input:
Is PAT&TAP symmetric?
Sample Output:
11

算法设计:

遍历输入的字符串S,以遍历到的当前字符为回文中心,不断向字符串两端延伸通过判断两侧字符是否相同即可得出以此字符为中心的最长回文子串,显然,这种回文子串长度一定是奇数。考虑长度为偶数的回文子串,以遍历到的当前字符为回文中心左侧字符,以当前字符的下一个字符为回文中心右侧字符,不断向字符串两端延伸通过判断两侧字符是否相同即可得出以此字符为回文中心左侧字符的最长回文子串。在上述遍历过程中,不断更新回文子串的最大长度,最后输出即可。

c++代码:

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s;
    getline(cin,s);
    int maxLen=0;
    for(int i=0;i<s.size();++i){
        int j;
        for(j=1;i-j>=0&&i+j<s.size()&&s[i+j]==s[i-j];++j);//以当前字符为回文中心查找最长回文子串
        maxLen=max(maxLen,2*j-1);//更新回文子串最大长度
        for(j=0;i-j>=0&&i+j+1<s.size()&&s[i-j]==s[i+1+j];++j);//以当前字符为回文中心左侧字符查找最长回文子串
        maxLen=max(maxLen,2*j);//更新回文子串最大长度
    }
    printf("%d",maxLen);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/richenyunqi/article/details/80218079