👨‍💻 738LeetCode

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.


Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c"
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa"


class Solution:
    def countSubstrings(self, s: str) -> int:
        dp = [[False] * len(s) for _ in range(len(s))]
        count = []
        for j in range(len(s)):
            dp[j][j] = True
            for i in range(0, j):
                if j - i == 1 and s[i] == s[j]:
                    dp[i][j] = s[i] == s[j]
                    count.append(s[i:j + 1])
                    dp[i][j] = s[i] == s[j] and dp[i + 1][j - 1]
                    if dp[i][j]:
                        count.append(s[i:j + 1])
        return len(count)


Simple change from Longest Palindromic Substring Q. Instead of only saving the longest one, save all substrings.