LeetCode 647. Palindromic Substrings

Posted A-Little-Nut

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 647. 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.

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.

分析

dp[i][j] 如果等于1就表示 string s 从下标i到j的那部分是 palindromic 的,而 string s 从 m 到 n 的部分只需要满足 s[m]==s[n] 并且 dp[m+1][n-1]==1 (即首尾相等,并且中间的是 palindromic )就是palindromic.

class Solution{
private:
    int dp[1000][1000];
public:
    int countSubstrings(string s) {
        for(int i=0;i<s.size();i++)
            dp[i][i]=1;
        int cnt=s.size();
        for(int len=2;len<=s.size();len++)
            for(int i=0;i<=s.size()-len;i++)
                if(len==2&&s[i]==s[i+1]){
                    dp[i][i+1]=1;
                    cnt++;
                }else if(s[i]==s[i+len-1]&&dp[i+1][i+len-2]==1){
                    dp[i][i+len-1]=1;
                    cnt++;
                }
        return cnt;
    }   
};

以上是关于LeetCode 647. Palindromic Substrings的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 647. Palindromic Substrings

LeetCode 647. 回文子串(Palindromic Substrings)

Leetcode 647. Palindromic Substrings

[动态规划] leetcode 647 Palindromic Substrings

[Leetcode]647.Palindromic Substrings

[Leetcode]647.Palindromic Substrings