题目:
解决思路:采用中心扩展法,回文串的长度可能是奇数或偶数,对于每个字符,以其为中心向左右扩展,找到最长的回文子串,对于偶数长度的回文串,以两个字符为中心向左右扩展,记录最长的回文子串的起始位置和长度。
#include <string>
#include <utility>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
if (s.empty()) return "";
int start = 0; // 最长回文子串的起始位置
int maxLen = 1; // 最长回文子串的长度
for (int i = 0; i < s.size(); ++i) {
// 处理奇数长度的回文串
int len1 = expandAroundCenter(s, i, i);
// 处理偶数长度的回文串
int len2 = expandAroundCenter(s, i, i + 1);
// 取较长的回文串
int len = max(len1, len2);
// 更新最长回文子串的起始位置和长度
if (len > maxLen) {
maxLen = len;
start = i - (len - 1) / 2;
}
}
return s.substr(start, maxLen);
}
private:
// 中心扩展函数
int expandAroundCenter(const string& s, int left, int right) {
while (left >= 0 && right < s.size() && s[left] == s[right]) {
left--;
right++;
}
// 返回当前回文串的长度
return right - left - 1;
}
};