PAT Advanced 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.

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

解题思路,分奇数,偶数,进行遍历,向两边散开寻找

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    string s;int ans=1;
    getline(cin,s);
    for(int i=0;i<s.length();i++){
        int j,k;
        for(j=1;i-j>=0&&i+j<s.length();j++)/** 奇数 */
            if(s[i-j]!=s[i+j]) break;
        if(2*j-1>ans) ans=2*j-1;
        if(s[i]==s[i+1])/** 偶数 */
            for(k=1;i-k>=0&&i+k+1<s.length();k++)
                if(s[i-k]!=s[i+k+1]) break;
        if(2*k>ans) ans=2*k;
    }
    cout<<ans;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/littlepage/p/12220006.html