1040 Longest Symmetric String (25 分)
 

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:

Is PAT&TAP symmetric?
 
结尾无空行

Sample Output:

11
 
结尾无空行
 
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String s = reader.readLine();

        System.out.println(LongestSymmetricString(s).length());


    }

    public static String LongestSymmetricString(String s){
        int n = s.length(), max = 1, begin = 0;
        if (n < 2){
            return s;
        }
        boolean[][] dp = new boolean[n][n];
        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 = i + l - 1;
                if (j >= n) break;

                if (s.charAt(i) == s.charAt(j)){
                    if (l <= 2){
                        dp[i][j] = true;
                    }else {
                        dp[i][j] = dp[i+1][j-1];
                    }
                }

                if (dp[i][j] && l > max){
                    max = l;
                    begin = i;
                }
            }
        }

        return s.substring(begin,begin + max);
    }
}