647. Palindromic Substrings

本文介绍了一种通过动态规划方法高效计算字符串中所有回文子串数量的算法。给出两个示例说明如何使用该算法得出正确答案。此外,文章还提供了一个C++实现示例。

摘要生成于 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".
  • 这题比较简单,找出递推公式较为容易。dp[i] = dp[i-1] + (新增的数目).
class Solution {
public:
    bool isPalindromic(const char * start,const char *end){
        while(start <= end){
            if((*start) == (*end)){
                start++;
                end--;
            }else{
                return false;
            }
        }

        return true;
    }

    int countSubstrings(string s) {
        int n = s.size();
        vector<int> dp(n,1);

        dp[0] = 1;
        const char * start = s.c_str();
        for(int i = 1; i < n;++i){
            const char * end = start + i;
            dp[i] = dp[i-1];
            for(int j = 0; j <= i; j++){
                if(isPalindromic(start+j,end)){
                    dp[i] += 1;
                }
            }
        }

        return dp[n-1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值