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:

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

dp[i][j]代表s[i...j]能否形成palindromic substring。Dynamic programming掃描所有可能的substrings組合,如果s[i]==s[j]且s[i+1...j-1]是palindrome,s[i...j]就可以形成新的一個palindromic substring。

// Dynamic programming
int countSubstrings(string s) { // time: O(n^2); space: O(n^2)
    int n = s.size(), res = 0;
    vector<vector<bool> > dp(n, vector<bool>(n, false)); // dp[i][j]: s[i...j] is a palindrome
    for (int j = 0; j < n; ++j) {
        for (int i = j; i >= 0; --i) {
            if (s[i] == s[j]) {
                if (j - i < 2 || dp[i + 1][j - 1]) {
                    dp[i][j] = true;
                    ++res;
                }
            }
        }
    }
    return res;
}

掃描所有input string中的character postition當作一個可能的palindromic substring中心,如果s[i] == s[j],往左右擴張形成一個新的palindromic substring。

// Expand from the center
int countSubstrings(string s) { // time: (n^2); space: O(1)
    int n = s.size(), res = 0;
    for (int i = 0; i < n; ++i) {
        helper(s, i, i, res); // odd length
        helper(s, i, i + 1, res); // even length
    }
    return res;
}
void helper(string& s, int i, int j, int& res) {
    while (i >= 0 && j < s.size() && s[i] == s[j]) {
        ++res;
        --i, ++j;
    }
}

這題跟5. Longest Palindromic Substring基本上概念完全一樣,求所有palindromic substrings數量相對簡單。

Last updated

Was this helpful?