PAT 甲级 1040 Longest Symmetric String

https://pintia.cn/problem-sets/994805342720868352/problems/994805446102073344

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 <bits/stdc++.h>
using namespace std;

string s;

int main() {
    getline(cin, s);
    int len = s.length();

    int ans = 1, cnt = 1, out = 1;
    for(int i = 0; i < len; i ++) {
        int st = i, en = i;
        while(st >= 0 && en < len && s[st] == s[en]) {
            st --;
            en ++;
        }
        ans = max(ans, en - st + 1);
    }

    for(int i = 0; i < len - 1; i ++) {
        int stt = i, enn = i + 1;
        while(stt >= 0 && enn < len && s[stt] == s[enn]) {
            stt --;
            enn ++;
        }
        cnt = max(cnt, enn - stt + 1);
    }

    out = max(ans, cnt);
    printf("%d\n", out - 2);
    return 0;
}

  这个题好像很久之前就开过来一直没写出来 可能是猪脑子吧

猜你喜欢

转载自www.cnblogs.com/zlrrrr/p/10163682.html