图片说明

import java.util.*;

public class Solution {
    public int getLongestPalindrome(String A, int n) {
        // write code here
        if (n < 2) {
            return n;
        }

        char[] a = A.toCharArray();
        boolean[][] dp = new boolean[n][n]; // 从下标i到j是否为回文串
        int max = 1;

        for (int i = 0; i < n; i++) {
            dp[i][i] = true;
        }

        for (int l = 2; l <= n; l++) {
            for (int i = 0; i < n; i++) {
                int j = l + i - 1;

                if (j >= n) {
                    break;
                }

                if (a[i] != a[j]) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }

                    if (dp[i][j] && max < j - i + 1) {
                        max = j - i + 1;
                    }
                }
            }
        }

        return max;
    }
}