LeetCode47动态规划-回文子串-回文子序列

647. 回文子串

力扣题目链接

class Solution {
    public int countSubstrings(String s) {
        //dp[i][j] [i ,j]区间里面的字符串是不是回文字符串
        //if(s.charAt(i ) != s.charAt(j ))dp[i][j] = false;
        //else if(j - 1 <= 1)dp[i][j] = true;
        //else dp[i][j] = dp[i + 1,j - 1]

        //初始化为false
        //依赖i + 1与 j - 1 左下角
        //从下到上,从左到右,下到上要在外层,j>=i

        int len = s.length();

        int result = 0;
        boolean[][] dp = new boolean[len][len];


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

516.最长回文子序列

力扣题目链接
 

class Solution {
    public int longestPalindromeSubseq(String s) {
        //dp[i][j] [i,j]区间内最长回文子序列
        //if(s.charAt(i) == s.charAt(j))dp[i][j] = dp[i - 1][j - 1] + 2;
        //else dp[i][j] = Math.max(dp[i - 1][j],dp[i][j - 1]);

        int len = s.length();
        int[][] dp = new int[len + 1][len + 1];

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

                    dp[i][j] = Math.max(dp[i][j],dp[i][j - 1]);
                    dp[i][j] = Math.max(dp[i + 1][j],dp[i][j]);
                }
            }
        }
    return dp[0][len - 1];
    }
}

你可能感兴趣的:(动态规划,算法)