自己想的,有可能是最好理解的解法:
1.遍历字符串,以当前字符作为单中心,或者双中心的左支点
2.获取以当前字符作为中心的回文子串的长度
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @return int整型
*/
int getLongestPalindrome(string A) {
// write code here
int res = 0;
for(int i=0;i<A.length();i++){
int tmp = max(getLongestPalindromeWithPosition(A, i, i),getLongestPalindromeWithPosition(A, i, i+1));
res = max(res,tmp);
}
return res;
}
int getLongestPalindromeWithPosition(string A,int i,int j){
int res = 0;
int m = i;
int n = j;
while(m >=0 && n <= A.length()-1 && A[m]==A[n]){
if(m==n){
res += 1;
}else{
res += 2;
}
m--;
n++;
}
return res;
}
};



京公网安备 11010502036488号