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

{% hint style="info" %}
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".
```

{% endhint %}

### Thought Process

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MNRQ3Pr_GXk9CpEhKjV%2F-MNRUJ-VFlAgR0aMrNLr%2FIMG_72DCB3817233-1.jpeg?alt=media\&token=ea980d11-11e3-4f57-8c2d-613861f8da4e)

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MNRQ3Pr_GXk9CpEhKjV%2F-MNRUeHvFHjuw8UWQX6i%2FIMG_26A56595D0E4-1.jpeg?alt=media\&token=1d54357a-c702-4e1b-b2b4-7e43e9c55a61)

## 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)
```
