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

文章目录

  • 零、原题链接
  • 一、题目描述
  • 二、测试用例
  • 三、解题思路
  • 四、参考代码

零、原题链接


HJ85 最长回文子串

一、题目描述

HJ85 最长回文子串【牛客网】_第1张图片

二、测试用例

HJ85 最长回文子串【牛客网】_第2张图片

三、解题思路

  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 
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")

你可能感兴趣的:(华为笔试练习,算法,C++,回文串,牛客网)