Problem Link

Description


Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward.

A substring is a contiguous sequence of characters within the string.

Β 

Example 1:

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

Example 2:

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

Β 

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

Solution


Python3

class Solution:
    def countSubstrings(self, s: str) -> int:
        N = len(s)
 
        @cache
        def isPal(i, j):
            if i == j: return True
            if i > j: return True
 
            return s[i] == s[j] and isPal(i + 1, j - 1)
        
        res = 0
 
        for i in range(N):
            for j in range(i, N):
                if isPal(i, j):
                    res += 1
        
        return res