方法一:动态规划
class Solution:
def countSubstrings(self, s: str) -> int:
cnt = 0
n = len(s)
dp = [[False for i in range(n)] for j in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
if s[i] == s[j] and (j - i <= 1 or dp[i + 1][j - 1]):
cnt += 1
dp[i][j] = True
return cnt
方法二:中心拓展
class Solution:
def countSubstrings(self, s: str) -> int:
def speard(l, r):
cnt = 0
while l >= 0 and r < len(s):
if s[l] == s[r]:
# print(s[l: r + 1]) # 左闭右开
l -= 1
r += 1
cnt += 1
else:
break
return cnt
ans = 0
for i in range(len(s)):
ans += speard(i, i) # 中心是一个字符;
ans += speard(i, i + 1) # 中心是2个字符;
return ans
方法三:暴力破解
class Solution:
def isPalindrome(self, s, low, high):
return s[low: high] == s[high: low: -1]
def countSubstrings(self, s: str) -> int: # 暴力解法
cnt = 0
for i in range(len(s)):
for j in range(i + 1):
if self.isPalindrome(s, j, i):
cnt += 1
return cnt