1. 程式人生 > >PAT A1040 最長子迴文串

PAT A1040 最長子迴文串

迴文串

正反看都一樣的字串稱作迴文串
有AA,ABA兩種形式:

  • AA
    形如 xxxxAAxxxx

  • ABA
    形如 XXXXABAxxxx

A1040 Longest Symmetric String

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

題意

給出一個字串,求出最長的子迴文串有多長

思路

  1. 迴文串一定是對稱的
  2. 迴文串的對稱中心是 AA 或 ABA
  3. 從對稱中心向兩邊延伸回文串,記錄下最長的長度

完整程式碼

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>  
#include <set>
#include <cstdio>

using namespace std;


int longestSS(const string& s)
{
    int
left, right; int length = s.length(); int _max = 1; //#1 xxxxxaaxxxx for (size_t core = 0; core < length; core++) { left = core; right = core + 1; while (left >= 0 && right < length && s[left] == s[right]) { int currentLength = right - left + 1; _max = currentLength > _max ? currentLength : _max; --left; ++right; } } //#2 xxxxxabaxxx for (size_t core = 0; core < length; core++) { left = core - 1; right = core + 1; while (left >= 0 && right < length && s[left] == s[right]) { int currentLength = right - left + 1; _max = currentLength > _max ? currentLength : _max; --left; ++right; } } return _max; } int main() { string s; getline(cin, s); cout << longestSS(s); system("pause"); return 0; }