java算法--动态规划之最长回文子串

最长回文算法

 public String longestPalindrome(String s) {
        int len = s.length();
        
        if (len == 0 || len == 1) {
            return s;
        }
        
        int maxend = 0;
        int maxLen = 0;

        int[][] dp = new int[len][len];

        String reverseStr = new StringBuffer(s).reverse().toString();

        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                if (s.charAt(i) == reverseStr.charAt(j)) {
                    if (i == 0 || j == 0) {
                        dp[i][j] = 1;
                    } else {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                    }
                }

                if (dp[i][j] > maxLen) {
                    int PreReverseIndex = len -1 - j;
                    if (PreReverseIndex + dp[i][j] -1 == i) {
                        maxLen = dp[i][j];
                        maxend = i;
                    }
                }
            }
        }

        return s.substring(maxend - maxLen + 1, maxend + 1);
        
    }

 

你可能感兴趣的:(java算法编程,java)