647. 回文子串
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
示例 1:
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
示例 2:
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
注意:
- 输入的字符串长度不会超过1000。
解题思路1:动态规划。令dp[i][j]表示以s[i]开头s[j]结尾的字符串是否为回文串,那么dp[i][j] = dp[i+1][j-1] and s[i] == s[j]。初始化dp[i][j]为True,从底至顶(或者从左至右)根据递推关系重置dp数组。
Python3代码如下:
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
N = len(s)
result = 0
dp = [[True]*N for i in range(N)]
for i in range(N-2,-1,-1):
for j in range(i+1,N):
dp[i][j] = dp[i+1][j-1] and s[i] == s[j]
for i in range(N):
for j in range(i,N):
if dp[i][j]:
result += 1
return result
解题思路2:令result[i]代表以s[i]为中心和以s[i]s[i+1]为中心的回文串的个数和,遍历s,对所有result[i]求和。
Python3代码如下:
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
def countSubstringsHelper(left,right,counter):
while left >= 0 and right < len(s) and s[left] == s[right]:
counter += 1
left -= 1
right += 1
return counter
result = 0
for i in range(len(s)):
result = countSubstringsHelper(i,i,result)
result = countSubstringsHelper(i,i+1,result)
return result