1. 程式人生 > >LC 647. Palindromic Substrings

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.

題目就是給一個字串,問裡面都多少個迴文子串。

 

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;
    }
};