给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"
示例 2:
输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
输入的字符串长度不会超过 1000 。
丢人法
class Solution: def countSubstrings(self, s: str) -> int: def ok(s): return s==s[::-1] def substrings(s): results = [] num = 0 for x in range(len(s)): for i in range(len(s) - x): results.append(s[i:i + x + 1]) return results a=substrings(s) res=0 for i in a: if ok(i): res+=1 return res
中心扩散法
class Solution: res=0 def countSubstrings(self, s: str) -> int: for i in range(len(s)): self.count(s,i,i) self.count(s,i,i+1) return self.res def count(self,s,start,end): while start>=0 and end<len(s) and s[start]==s[end]: self.res+=1 start-=1 end+=1
class Solution: def countSubstrings(self, s: str) -> int: res=0 for i in range(len(s)*2-1): l=i//2 r=i//2+i%2 while l>=0 and r<len(s) and s[l]==s[r]: res+=1 l-=1 r+=1 return res
dp
class Solution: def countSubstrings(self, s: str) -> int: dp=[0] for i in range(1,len(s)+1): res=0 for j in range(i): if s[j:i]==s[j:i][::-1]: res+=1 dp.append(dp[-1]+res) return dp[-1]
class Solution: def countSubstrings(self, s: str) -> int: return reduce(lambda n,i:n+sum(s[j:i]==s[j:i][::-1] for j in range(i)),range(1,len(s)+1),0)