Palindromic Substrings

来源:互联网 发布:mac安装pip ipython 编辑:程序博客网 时间:2024/06/05 04:30

题目描述

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;    }};
原创粉丝点击