Palindromic Substrings

Problem

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.

For example:

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

Thought Process

Solution

class Solution:
    def countSubstrings(self, s: str) -> int:
        dp = [[False for j in range(len(s))] for i in range(len(s))]
        
        count = 0
        
        for i in range(len(s)-1,-1,-1):
            dp[i][i] = True
            count+=1
            for j in range(i+1,len(s)):
                if s[i] == s[j]:
                    if j-i == 1 or dp[i+1][j-1] == True: #the substring in between is a palindorme
                        dp[i][j] = True
                        count+=1
        return count


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

Last updated

Was this helpful?