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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值