# 647\_Palindromic Substrings

## 647. Palindromic Substrings

Level: medium

Tag: string, dynamic programming

## Question

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

Note: A **palindrome** is a word, which **reads the same backward as forward**.

### Example1

```
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
```

### Example2

```
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
```

### Idea: (expand around center, dynamic programming, similar to Longest Palindromic Substring Q5)

Loop from the beginning to the end. Take each letter be the center of the substring, and find the number of palindromic substring centered by that letter.

There are two types of center:

* the letter is the center, such that the palindromic substring has odd number of letters
* the space on the right of the letter is the center, such that the palindromic substring has even number of letters

### Complexity

* Time:$$O(n^2)$$
* Space:$$O(1)$$

### Solution

```python
class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0

        # dynamic programming
        for i in range(len(s)):
            count += self.helper(s,i,i+1) + self.helper(s,i,i)
        return count




        # helper function to get the number of palindromic substring expanding from s[l:r+1]
        # from center to outer letters
    def helper(self, s, l, r):
        """
        :type s: str
        :type l: num
        :type r: num
        :rtype: str
        """
        count = 0
        while l >= 0 and r <= len(s)-1 and s[l] == s[r]:
            count += 1
            l -= 1
            r += 1
        return count
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lei-d.gitbook.io/leetcode/string/647palindromic-substrings.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
