对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
非马拉车来解最长对称子串,比较暴力的方式,在看的时候还看到了用dp的方式
int max=1;//★★★★★非空字符串,最短对称子串的长度为1,否则样例会有一个不过
---------------------
如果子串偶对称
for(int i=0;i<len;i++)
{
int x=i,y=i+1;
int ans=0;
while(s[x]==s[y]&&x>=0&&y<len)
{
x--;
y++;
ans+=2;
}
if(ans>max)
{
max=ans;
}
}
---------------------
如果子串奇对称
for(int i=1;i<len;i++)
{
int x=i-1,y=i+1;
int ans=1;//答案先加上中间的那个字符
while(s[x]==s[y]&&x>=0&&y<len)
{
x--;
y++;
ans+=2;
}
if(ans>max)
{
max=ans;
}
}
ac代码:
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f;
int main()
{
string s;
getline(cin,s);
int len=s.size();
int max=1;
for(int i=0;i<len;i++)
{
int x=i,y=i+1;
int ans=0;
while(s[x]==s[y]&&x>=0&&y<len)
{
x--;
y++;
ans+=2;
}
if(ans>max)
{
max=ans;
}
}
for(int i=1;i<len;i++)
{
int x=i-1,y=i+1;
int ans=1;
while(s[x]==s[y]&&x>=0&&y<len)
{
x--;
y++;
ans+=2;
}
if(ans>max)
{
max=ans;
}
}
cout<<max;
return 0;
}
马拉车算法
#include <iostream>
#include <cstdio>
#include <cstring>
#define MAX 1000
using namespace std;
char s[MAX + 1];
char t[MAX * 2 + 5] = {'@','#'};
int p[MAX * 2 + 5];
int Manacher(char *str) {
int len = strlen(str);
for(int i = 1;i <= len;i ++) {
t[i * 2] = str[i - 1];
t[i * 2 + 1] = '#';
}
t[len * 2 + 2] = 0;
int mi = 0,rpoint = 0,mr = 0;
for(int i = 1;t[i];i ++) {
p[i] = i < rpoint ? min(rpoint - i,p[mi * 2 - i]) : 1;
while(t[i + p[i]] == t[i - p[i]]) p[i] ++;
if(i + p[i] > rpoint) {
mi = i;
rpoint = i + p[i];
}
if(mr < p[i]) mr = p[i];
}
return mr - 1;
}
int main() {
int i = 0;
while((s[i] = getchar()) != '\n') i ++;
s[i] = 0;
printf("%d",Manacher(s));
}