力扣leetcode 5. 最长回文子串 java

力扣leetcode 5. 最长回文子串 java_第1张图片

class Solution {
    public String longestPalindrome(String s) {
        if(s.length() == 0) return "";
        int[][] dp = new int[s.length()][s.length()];
        int start = 0, maxLen = 1;
        for(int i=0; i<s.length(); i++) {
            dp[i][i] = 1;
            if(i > 0 && s.charAt(i-1) == s.charAt(i)) {
                dp[i-1][i] = 1;
                start = i-1;
                maxLen = 2;
            }
        }
        for(int l=3; l<=s.length(); l++) {
            for(int i=0, j=i+l-1; j<s.length(); i++, j++) {
                if(s.charAt(i) == s.charAt(j) && dp[i+1][j-1] == 1) {
                    dp[i][j] = 1;
                    start = i;
                    maxLen = l;
                }
            }
        }
        return s.substring(start, start+maxLen);
    }
}

你可能感兴趣的:(每日一题leetcode)