零、原题链接
一、题目描述
二、测试用例
三、解题思路
- 基本思路:
中心扩展法 - 具体思路:
- 编写获得回文串长度的函数
int GetLen(const string& str, int pre, int next)
:- 如果
pre
和next
坐标合法,且坐标上的元素相同,则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")