回文子串问题(动态规划

回文子串(最长回文字串

Dp[i][j]表示i到j是否是回文字串,左闭右闭区间

回文字串三种情况:1 i=j 是 2.i与j相差一个位置是

  1. i与j相差很多个,判断区间里是否是回文字串

遍历顺序由递推公式来决定,所以可以画图看看

class Solution {
    public int countSubstrings(String s) {
        char[] c1=s.toCharArray();
        int len=c1.length;
        int res=0;
        boolean[][] dp=new boolean[len][len];//dp[i][j]表示i到j是这个范围是不是回文字串
        for(int i=len-1;i>=0;i--){
            for(int j=i;j<len;j++){
                if(c1[i]==c1[j]){//先判断所指向的元素是否相等
                    if(j-i<=1){
                    dp[i][j]=true;
                    res++;
                }else if(dp[i+1][j-1]){
                        dp[i][j]=true;
                        res++;
                    }
                }
                }
            }
        return res;
    }
}

回文子串(最长回文子序列 ,可以不连续

求最长回文子序列的长度,如果i和j指向的数相等则+2,不能则取最大值(i+1,j-1)

初始化,i和j相等时为1

class Solution {
    public int longestPalindromeSubseq(String s) {
        char[] c=s.toCharArray();
        int len=c.length;
        int[][] dp=new int[len][len];//i到j的最长回文子序列
        for(int i=len-1;i>=0;i--){
            dp[i][i]=1;//初始化
            for(int j=i+1;j<len;j++){
                if(c[i]==c[j]){
                    dp[i][j]=dp[i+1][j-1]+2;
                }else{
                    dp[i][j]=Math.max(dp[i+1][j],dp[i][j-1]);
                }
            }
        }
        return dp[0][len-1];
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值