回文子串 Palindromic Substrings
方法1:暴力 - 需要三层循环
- 该方法会超时
class Solution:
def countSubstrings(self, s: str) -> int:
dp = [0] * len(s)
dp[0] = 1
for i in range(1, len(s)):
dp[i] = dp[i-1]
for j in range(i, -1, -1):
a = i
b = j
key = True
while a > b:
if s[a] != s[b]:
key = False
break
a -= 1
b += 1
if key:
dp[i] += 1
return dp[-1]
方法2:记忆化回溯 (备忘录递归)
class Solution:
def countSubstrings(self, s: str) -> int:
dp = [0] * len(s)
dp[0] = 1
memo_dict = {}
for i in range(1, len(s)):
dp[i] = dp[i-1]
for j in range(i, -1, -1):
if s[i] == s[j] and (i-j<=1 or (j+1, i-1) in memo_dict):
if (j, i) not in memo_dict:
memo_dict[(j, i)] = 1
dp[i] += 1
return dp[-1]
方法4:双指针,从中间向两端扩展
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
self.res = 0
def helper(i, j):
while i >= 0 and j < n and s[i] == s[j]:
self.res += 1
i -= 1
j += 1
for i in range(n):
helper(i, i)
helper(i, i + 1)
return self.res