【leetCode】5_最长回文字符串

class Solution {
    public String longestPalindrome(String s) {
        int maxLength = 0, ti = 0, tj = 1;
        int strlen = s.length();
        int[][] dp = new int[strlen + 5][strlen + 5];
        for (int i = 0; i < strlen; i ++){
            for (int j = 0; j < 2; j ++){
                dp[i][i + j] = 1;
            }
        }
        for (int i = 1; i < strlen; i ++){
            dp[i][i - 1] = 1;
        }
        for(int k = 1; k <= strlen; k ++){
            for (int i = 0; i < strlen; i ++){
                if (i + k > strlen)
                    break;
                if (s.charAt(i) == s.charAt(i + k - 1)){
                    dp[i][k + i] = dp[i + 1][i + k - 1];
                    if ((dp[i][k + i] == 1) && (k > maxLength)) {
                        maxLength = k;
                        tj = k + i;
                        ti = i;
                    }
                }
                else{
                    dp[i][i + k] = 0;
                }

            }
        }

        if (strlen != 0)
            return s.substring(ti, tj);
        else
            return "";
    }
}

 

你可能感兴趣的:(leetCode)