最长回文子串 【朴素算法(枚举)】

本文介绍了一种求解字符串中最长回文子串的方法,通过枚举中间字符并检查两侧字符是否对称来确定回文串。文章提供了一个完整的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。
输入一个字符串Str,输出Str里最长回文子串的长度。
Input
输入Str(Str的长度 <= 1000)
Output
输出最长回文子串的长度L。
Sample Input
daabaac
Sample Output
5
思路: 朴素算法 ,我们可以枚举处于中间的数是哪个,对于aba型的,枚举b(可以从第一个位置到最后一个位置) ; 对于abba 可以枚举中间的数是哪个
代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#define CLR(a,b) memset((a),(b),sizeof(a))
#define inf 0x3f3f3f3f
#define mod 100009
#define LL long long
#define M  10000
#define ll o<<1
#define rr o<<1|1
#define lson o<<1,l,mid
#define rson o<<1|1,mid+1,r
using namespace std;
char s[M];
int main()
{
    gets(s);   //最长回文子串 
    int len=strlen(s);
    int i,j;int ans=0;
    for(i=0;i<len;i++) // 枚举中间数字的位置
    {
        for(j=1;i+j<len&&i-j>=0&&s[i+j]==s[i-j];j++) ;//aba型
        ans=max(ans,2*(j-1)+1);
        for(j=1;i+j<len&&i-j+1>=0&&s[i+j]==s[i-j+1];j++);//abba型
        ans=max(ans,2*(j-1)); 
    }
    printf("%d\n",ans==1?0:ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值