Palindromic Substrings

题目描述

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.

思路分析

问题是求解一个给定字符串的所有回文子字符串。
回文字符串是指一个字符串从头到尾,或者从尾到头是相同的,比如说level,aba等等。
我们可以利用动态规划的思想来解决。假设dp[m][n]==1表示字符串中从第m个字符到第n个字符的子字符串是回文,那么显然,对于每个单独的字符组成的字符串dp[i][i]==1;一般的状态转移方程:dp[i][j]==1当且仅当s[i]==s[j]且dp[i+1][j-1]==1(字符串的首尾相同,中间子字符串是回文),或者s[i]==s[j]且i+1>=j-1(字符串的长度不多于3)

代码实现

class Solution {
public:
    int countSubstrings(string s) {
        int size = s.size();
        int count = 0;  //统计回字串的数量
        int dp[size][size] = {0};   //dp[i][j]==1表示从i到j的子字符串是回文
        for (int j = 0; j < size; j++) {
            dp[j][j] = 1;
            count++;
            for (int i = 0; i < j; i++) {
                if (s[i] == s[j] && (((i+1) >= (j-1)) || (dp[i+1][j-1] == 1))) {
                    dp[i][j] = 1;
                    count++;
                }
            }
        }
        return count;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值