HJ85 最长回文子串【牛客网】

零、原题链接


HJ85 最长回文子串

一、题目描述

在这里插入图片描述

二、测试用例

在这里插入图片描述

三、解题思路

  1. 基本思路:
      中心扩展法
  2. 具体思路:
    • 编写获得回文串长度的函数 int GetLen(const string& str, int pre, int next)
      • 如果 prenext 坐标合法,且坐标上的元素相同,则 pre 坐标前移,next 坐标后移,直到不满足条件为止;
      • 返回回文串长度 next - pre - 1 ;
    • 遍历字符串:
      • 构建偶数长度的回文串,记录最长回文串长度;
      • 构建奇数长度的回文串,记录最长回文串长度;
    • 返回结果

四、参考代码

时间复杂度: O ( n 2 ) \Omicron(n^2) O(n2)
空间复杂度: O ( 1 ) \Omicron(1) O(1)

#include <iostream>
using namespace std;

int GetLen(const string& str, int pre, int next) {
    while (pre >= 0 && next < str.length() && str[pre] == str[next]) {
        pre--;
        next++;
    }

    return next - pre - 1;
}

int main() {
    string str;
    int _max = 1;
    cin >> str;

    for (int i = 1; i < str.length(); i++) {
        _max = max(_max, GetLen(str, i, i - 1));
        _max = max(_max, GetLen(str, i, i));
    }

    cout << _max;
}
// 64 位输出请用 printf("%lld")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值