647. Palindromic Substrings

本文介绍了一种算法,用于统计给定字符串中回文子串的数量,通过两种方法实现:暴力破解和动态规划。暴力破解法以每个字符为中心向两边扩展;动态规划则使用布尔型二维数组记录子串是否为回文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
 

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
 

Note:

The input string length won't exceed 1000.
 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindromic-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1. 暴力破解
对于每一个数字,以它为中心,向两边开始遍历,如果是循环串就统计加一。因为要区别奇数和偶数的情况,所以还有一种,以两个数字为中心,向两边遍历。

class Solution {
    private int ans = 0;
    public int countSubstrings(String s) {
        for (int i = 0; i < s.length(); i++) {
            search(i, i, s);
            search(i, i + 1, s);
        }
        return ans;
    }

    private void search(int i, int j, String s) {
        while (i >= 0 && j < s.length()) {
            if (s.charAt(i) == s.charAt(j)) {
                ans++;
                i--;
                j++;
            } else {
                return;
            }
        }
    }
}

2. 动态规划
用Boolean dp[i][j]表示字符串的i到j位是否是回文子串,那么
如果s.charAt(i) == s.charAt(j),那么dp[j][i] = dp[j + 1][i - 1],如果dp[j][i]是true,那么就最终结果加一。

class Solution {
    private int ans = 0;
    public int countSubstrings(String s) {
        boolean [][] dp = new boolean[s.length()][s.length()];
        for (int i = 0; i < s.length(); i++) {
            for (int j = 0; j <= i; j++) {
                if (i == j) {
                    dp[j][i] = true;
                    ans++;
                } else {
                    if (j + 1 == i) {
                        if (s.charAt(i) == s.charAt(j)) {
                            dp[j][i] = true;
                            ans++;
                        }
                    } else {
                        if (s.charAt(i) == s.charAt(j)) {
                            dp[j][i] = dp[j + 1][i - 1];
                            if (dp[j][i]) {
                                ans++;
                            }
                        }
                    }
                }
            }
        }
        return ans;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值