Skip to content

0647. 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.

Analysis

We create a 2D dp array, which stands for: if dp[i][j] == true, then s[i:j] is a palindrome.

  1. Outer loop: iterate over all the lengths (0 - n) for the substring.
  2. Inner loop: iterate over all the starting indexes of the substring. (ends at starting idx + length)

Edge case: when length <= 2, just set it to true and there is no need to check the previous state.

Time: O(n^2) Space: O(n^2)

Code

class Solution {
public:
    int countSubstrings(string s) {
        int n = s.size();
        bool pal[n][n];
        int res = 0;
        memset(pal, 0, sizeof pal);
        for (int d = 0; d < n; ++d) { // length
            for (int i = 0; i + d < n; ++i) { // start pos
                int j = i + d;
                if (s[i] == s[j]) { // if length <= 2 AND s[i] == s[j], simply set pal[i][j] to true
                    pal[i][j] = (d <= 2) || pal[i + 1][j - 1];
                }
                if (pal[i][j]) res ++;
            }
        }
        return res;
    }
};