回文串+动态规划

最长回文子串

遍历字符串,逐个判断每个字符,向两边扩散,判断以当前字符为中心,最长回文大小。 

/**
 * ①中心扩散法
 * 向左 向右 向左右
 * ②动态规划优化
 * 空间换时间
 */
class Solution {
    public static void main(String[] args) {
        System.out.println(longestPalindrome(new String("a")));
    }

    public static String longestPalindrome(String s) {
        if (s.length() < 2) return s;
        int l = 0, r = 0;
        int maxv = 1;
        for (int i = 0; i < s.length(); i++) {
            int left = i - 1, right = i + 1;
            int len = 1;
            //向左
            while (left >= 0 && s.charAt(left) == s.charAt(i)) {
                left--;
                len++;
            }
            //向右
            while (right < s.length() && s.charAt(right) == s.charAt(i)) {
                right++;
                len++;
            }
            //向左右
            while (right < s.length() && left >= 0 && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
                len += 2;
            }
            if (len > maxv) {
                maxv = len;
                l = left;
                r = right;
            }
        }
        return s.substring(l + 1, l + maxv + 1);
    }
}

动态规划的做法就是:记录已经遍历过的字符串,避免重复判断 

/**
 * ①中心扩散法
 * 向左 向右 向左右
 * ②动态规划优化
 * 空间换时间
 */
class Solution {
    public static String longestPalindrome(String s) {
        if (s.length() < 2) return s;
        int maxv = 1;
        int ll = 0, rr = 0;
        boolean dp[][] = new boolean[s.length()][s.length()];
        for (int r = 1; r < s.length(); r++) {
            for (int l = 0; l < r; l++) {
                if (s.charAt(l) == s.charAt(r) && (r - l <= 2 || dp[l + 1][r - 1])) {
                    dp[l][r] = true;
                    if (r - l + 1 > maxv) {
                        maxv = r - l + 1;
                        ll = l;
                        rr = r;
                    }
                }
            }
        }
        return s.substring(ll, rr + 1);
    }
}

 

 

你可能感兴趣的:(leetcode,每日总结,JAVA,动态规划,算法,leetcode)