最长回文子串
题目描述
对于长度为n的一个字符串A(仅包含数字,大小写英文字母),请设计一个高效算法,计算其中最长回文子串的长度。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @return int整型
*/
int getLongestPalindrome(string A) {
// write code here
}
};
中心扩展法
class Solution {
public:
int center_expand(int l, int r, const string& A) {
while (l >= 0 && r < A.size() && A[l] == A[r]) {
--l;
++r;
}
return r - l - 1;
}
int getLongestPalindrome(string A) {
int sz = A.size();
int _max = 1;
for (int i = 0; i < sz - 1; ++i) {
_max = max(_max, center_expand(i, i, A));
_max = max(_max, center_expand(i, i + 1, A));
}
return _max;
}
};