Problem E : Find Palindrome
From:
DHUOJ, 2017060305
Description
Given a string S, which consists of lowercase characters, you need to find the longest palindromic sub-string.
A sub-string of a string S is another string S' that occurs "in" S. For example, "abst" is a sub-string of "abaabsta". A palindrome is a sequence of characters which reads the same backward as forward.
Input
There are several test cases.
Each test case consists of one line with a single string S (1 ≤ |S | ≤ 50).
Output
For each test case, output the length of the longest palindromic sub-string.
Sample Input
sasadasa bxabx zhuyuan
Sample Output
7 1 3
Author: Kenny
利用dp来记录当前位置的最长回文串长度
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MIN(a,b) ((a) < (b) ? (a) : (b))
int maxid; // 最长回文子串下标
int LPS_rb[100]; // i为中心的回文子串右边界下标right border
char str[100]; // 原字符串处理后的副本
int maxlen;
void LPS_linear(char * X, int xlen)
{
maxlen = maxid = 0;
str[0] = '$'; // 将原串处理成所需的形式
char *p = str;
*(++p)++ = '#';
while((*p++ = *X++) != '\0')
{
*p++ = '#';
}
for(int i = 1; str[i]; ++i) // 计算LPS_rb的值
{
if(maxlen > i) // 初始化LPS[i]
{
LPS_rb[i] = MIN(LPS_rb[2*maxid-i],(maxlen-i));
}else
{
LPS_rb[i] = 1;
}
while(str[i-LPS_rb[i]] == str[i+LPS_rb[i]]) // 扩展
{
++LPS_rb[i];
}
if(LPS_rb[i]-1 > maxlen)
{
maxlen = LPS_rb[i]-1;
maxid = i;
}
}
}
int main(){
char s[51];
while(cin>>s){
LPS_linear(s,strlen(s));
printf("%d\n", maxlen);
}
return 0;
}