2022.02.26 - SX10-52.回文子串

1. 题目

在这里插入图片描述

2. 思路

(1) 动态规划

  • dp[i][j]表示字符串s的下标为[i,j]的子串是否是回文子串。
  • 当chars[i]==chars[j]且下标为[i+1,j-1]的子串是回文子串时,可判定下标为[i,j]的子串也是回文子串,即dp[i][j]=true。

3. 代码

public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    public int countSubstrings(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        boolean[][] dp = new boolean[n][n];
        int count = 1;
        dp[n - 1][n - 1] = true;
        for (int i = n - 2; i >= 0; i--) {
            dp[i][i] = true;
            count++;
            if (chars[i] == chars[i + 1]) {
                dp[i][i + 1] = true;
                count++;
            }
            for (int j = i + 2; j < n; j++) {
                if (chars[i] == chars[j] && dp[i + 1][j - 1]) {
                    dp[i][j] = true;
                    count++;
                }
            }
        }
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值