回文串
正反看都一样的字符串称作回文串
有AA,ABA两种形式:
AA
形如 xxxxAAxxxxABA
形如 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
题意
给出一个字符串,求出最长的子回文串有多长
思路
- 回文串一定是对称的
- 回文串的对称中心是 AA 或 ABA
- 从对称中心向两边延伸回文串,记录下最长的长度
完整代码
#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;
}