classSolution:defcountSubstrings(self,s:str) ->int: res =0for i inrange(len(s)): res += self.palindromic(s, i, i) res += self.palindromic(s, i, i+1)return resdefpalindromic(self,s,i,j): temp_res =0while i >=0and j <len(s)and s[i]== s[j]: temp_res +=1 i -=1 j +=1return temp_res
时间复杂度:O()
空间复杂度:O()
# 字符串dp: 注意二维dp和一维字符串性质一起对应起来, dp[i][j]:表示左闭右闭区间范围[i,j]的子串是否是回文子串classSolution:defcountSubstrings(self,s:str) ->int: dp = [[False] *len(s)for _ inrange(len(s))] result =0for i inrange(len(s)-1, -1, -1):# 注意遍历顺序for j inrange(i, len(s)):if s[i]== s[j]:if j - i <=1: result +=1 dp[i][j] =Trueelif dp[i+1][j-1]: result +=1 dp[i][j] =Truereturn result