回文子串是中心对称的,比如aba,abba,所以区分奇数和偶数,值得注意的是单字符也是中心对称的。

  • 判断奇数回文子串,中间的数只有一个,分别向两边扩散,直到左边到第一个位置,假设中间的数在第i位,i-1位置上的数和i+1位置上的数一致,回文子串的长度就可加2,所以这里要循环,假设i-1为x,i+1为y,那么直到x--等于0时或者x位置上的数不等于y位置上的数时即可结束循环,此时计算的长度为最大回文长度,赋给max,依次循环,下次计算的长度大于max时赋值即可
  • 判断偶数回文子串,中间的数是2个,再分别向两边扩散,所以中间的数是i和i+1,其他同上
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param A string字符串 
     * @return int整型
     */
    public int getLongestPalindrome (String A) {
        // write code here
        int m = A.length();
        int max=0;
        for(int i=0;i<m;i++){
//             奇数对称
            int x=i-1,y=i+1,count=1;
            while(x>=0 && y<m){
                if(A.charAt(x)==A.charAt(y)){
                    x--;
                    y++;
                    count+=2;
                }else{
                    break;
                }
            }
            if(count>max)max=count;
//             偶数对称
            int a=i,b=i+1,count1=0;
            while(a>=0 && b<m){
                if(A.charAt(a)==A.charAt(b)){
                    a--;
                    b++;
                    count1+=2;
                }else{
                    break;
                }
            }
            if(max<count1)max=count1;
        }
        return max;
    }
}

简化后代码如下

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param A string字符串 
     * @return int整型
     */
    public int getLongestPalindrome (String A) {
        // write code here
        int m = A.length();
        int max=0;
        for(int i=0;i<m;i++){
//             奇数对称
            int count = getMax(A,i-1,i+1,1);
            if(count>max)max=count;
//             偶数对称
            count = getMax(A,i,i+1,0);
            if(count>max)max=count;
        }
        return max;
    }
    
    public int getMax(String A,int x,int y,int count){
        while(x>=0 && y<A.length()){
            if(A.charAt(x--)==A.charAt(y++)){
                count+=2;
            }else{break;}
        }
        return count;
    }
}