647. Palindromic Substrings (DP)

来源:互联网 发布:淘宝网店上货教程 编辑:程序博客网 时间:2024/04/30 02:44

1.Description

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.

2. Analysis

分析并不难,采用自底向上的方法,从简单到复杂,从小规模到大规模。假如输入的string长度为1,那么显然result=1,假如为2,那么result可能为2也可能为3。假如为3,那么result可能为3,4,6。举例:“aba”为4,“abc”为3,“aaa”为6。(注意没有5,为什么)。我们假设f(1)="a", f(2)="ab", f(3)="abc", f(4)="abcb",那么|f(1)|=1,|f(2)|=2,|f(3)|=3,|f(4)|=3+1+1=5,可见f(4) 可以在f(3)的基础上只对n=4的情况计算,而不需要全部计算。也就是只要从n=4开始,找出以4为开头的[4…1]序列的回文子串。如:[b], [b,c,b],再加上f(3)的结果,也就是等于5。

所以状态转移方程可用下列表示:

f(n)=f(n1)+g(n)

g(n)表示寻找以str[n]为首的回文子串。


3. Code

class Solution {public:    static int recur(string& str, int e) {        int ret = 0;        for(int i = e; i >= 0; i--) {             int count = 0;//成对的数是否满足回文            //分奇偶            if((e-i)%2==0) {                int mid = (e+i)/2;                for(int j = 0; mid-j >= 0 && mid + j <= e && str[mid-j] == str[mid + j]; j++) {                    count++;                }            } else {                for(int j = i, k = e; j < k && str[j] == str[k]; j++, k--) {                    count++;                }            }             if(count == (e-i)/2 + 1) //满足回文,ret加1                    ret++;        }        return ret;    }    int countSubstrings(string s) {        int n = s.length();        int res[n+1] = {0};        for(int i = 1; i <= n; i++) {            res[i] = recur(s, i-1) + res[i-1];        }        return res[n];    }};
原创粉丝点击