1. 程式人生 > >PAT 甲級 1040 Longest Symmetric String

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;
}

  這個題好像很久之前就開過來一直沒寫出來 可能是豬腦子吧