LC 647. Palindromic Substrings

1.题目描述

647. Palindromic Substrings

Medium

103156FavoriteShare

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:

  1. The input string length won't exceed 1000.

题目就是给一个字符串,问里面都多少个回文子串。

扫描二维码关注公众号,回复: 4464361 查看本文章

2.解题思路

用动态规划的思路。虽然字符串是一维线性结构,但是考虑这个问题时要用二维的思路去考虑。dp[i][j]表示从第i个字符到第j个字符构不构成回文子串,若构成则赋值1,否则赋值0。注意i<=j。所以并不是要计算整个dp数组,而是计算这个数组的上半部分。

可以发现这样的规律:

dp[  i ][ j ] = 1, 若s[ i ]==s[ j ] 且 dp[ i+1 ][ j-1 ] == 1.

否则dp[ i ][ j ] = 0

要注意还有一种特殊情况dp[ i ][ j ] = 1;那就是去掉s[ i ] 和 s[ j ]之后为空串。所以把上面dp[ i ][ j ] = 1的情况改为:

dp[  i ][ j ] = 1, 若s[ i ]==s[ j ] 且 (dp[ i+1 ][ j-1 ] == 1 或  j - i ==1)

每次给dp赋值1的时候计数,赋值0则不计数

最后返回计数即可

3.实现代码

class Solution {
public:
    int countSubstrings(string s) {//要用二维dp数组
        int num = s.size();
        int res = 0;
        int dp[num][num];//dp[i][j]表示s[i]到s[j]是否构成回文串
        memset(dp, 0, sizeof(dp));
        for (int i=0; i<num; i++) { 
            dp[i][i] = 1;
            res++;
        }
        for (int i=num-1; i>=0; i--) {//注意遍历顺序,行从最下面开始,列从最左面开始
            for (int j=i+1; j<num; j++) {
                if (s[i]==s[j]&&(dp[i+1][j-1]==1 || j-i==1)) {
                    dp[i][j] = 1;
                    res++;
                }
                else {
                    dp[i][j] = 0;
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41814429/article/details/84953509