题目描述
给你一个字符串s, 找到s中最长的回文子串。
举例:
eg.1 s = "babad" ==> "bab"
eg.2 s = "cbbd" ==> "bb"
eg.3 s = "aaabcdadcbabbb" ==> "abcdadcba"
解题思路: 中心扩展法。将某一个字符,从中间向左右两端扩展,记录满足回文条件的最大的长度和对应的子串,并将最长的子串返回。
代码
#include <iostream>
#include <string>
int expand_around_center(const std::string& str, int left, int right) {
int n = str.size();
if (n <= 0 || left < 0 || right >= n) {
return 0;
}
int len = 0;
while (left >= 0 && right < n && str[left] == str[right]) {
left--;
right++;
}
len = (right - 1) - (left + 1) + 1; //这样写不容易出错
return len;
}
std::string max_palindrome(const std::string& str) {
int n = str.size();
if (n <= 0) {
return "";
}
int max_len = 0;
int start = 0;
for (int i = 0; i < n; i++) {
auto len1 = expand_around_center(str, i, i);
auto len2 = expand_around_center(str, i, i + 1);
auto len = std::max(len1, len2);
if (len > max_len) {
start = i - (len - 1) / 2; //这个是关键
max_len = len;
}
}
return str.substr(start, max_len);
}
int main()
{
//case1: s = "babad" ==> "bab"
auto str = "babad";str = "babad";
auto result = max_palindrome(str);
std::cout << str << "-->" << result << std::endl;
//case2: s = "cbbd" ==> "bb"
str = "cbbd";
result = max_palindrome(str);
std::cout << str << "-->" << result << std::endl;
//case3: s = "aaabcdadcbabbb" ==> "abcdadcba"
str = "aaabcdadcbabbb";
result = max_palindrome(str);
std::cout << str << "-->" << result << std::endl;
return 0;
}
代码运行结果如下:
babad-->bab
cbbd-->bb
aaabcdadcbabbb-->abcdadcba