647. Palindromic Substrings(Leetcode每日一题-2020.08.19)

Problem

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.

Note:

  • The input string length won’t exceed 1000.

Example1

Input: “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.

Example2

Input: “aaa”
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.

Solution

与5. Longest Palindromic Substring一样。

647. Palindromic Substrings(Leetcode每日一题-2020.08.19)_第1张图片

class Solution {
public:
    int countSubstrings(string s) {
        int len = s.length();
        if(len <=1)
            return len;
        int ret = 0;
        //定义isPanlindrome[i][j]表示s[i,...,j]是否是回文
        vector<vector<bool>> isPanlindrome(len,vector<bool>(len,false));

        //每个单独的字符都是回文
        for(int i = 0;i<len;++i)
        {
            isPanlindrome[i][i] = true;
            ++ret;
        }
        //从上到下,从左向右填充isPanlindrome的左上部分
        for(int j = 1;j<len;++j)
        {
            for(int i = 0;i<j;++i)
            {
                if(s[i] == s[j])
                {
                    if(j - i + 1 < 4)//s[i,..j]的长度小于4,一定是回文
                        isPanlindrome[i][j] = true;
                    else
                        isPanlindrome[i][j] = isPanlindrome[i+1][j-1];
                }

                if(isPanlindrome[i][j])
                {
                    ret++;
                }
            }
        }

        return ret;

    }
};

你可能感兴趣的:(leetcode动态规划,leetcode字符串)