Two methods:
expand center and dp
class Solution:def countSubstrings(self, s: str) -> int:def expandandCount(s, left, right):if right >= len(s):return 0ans = 0while left >= 0 and right < len(s) and s[left] == s[right]:ans += 1left -= 1right += 1return ansif not s:return 0n = len(s)ans = 0for i in range(n):ans += expandandCount(s, i, i)ans += expandandCount(s, i, i+1)return ans
class Solution:
def countSubstrings(self, s: str) -> int:
if not s:
return 0
n = len(s)
dp = [[False] * n for _ in range(n)]
for i in range(n-1, -1, -1):
dp[i][i] = True
for j in range(i+1, n):
if j == i + 1:
dp[i][j] = s[i] == s[j]
else:
dp[i][j] = dp[i+1][j-1] and s[i] == s[j]
result = sum([sum(dp[i]) for i in range(n)])
return result
