647. Palindromic Substrings
- Palindromic Substrings python solution
题目描述
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
解析
palindromic是回文的意思,本题让我们计算整个数列中有多少个回文数列。两个回文数列可能内容一致,但是只要数列中的元素在原数列中的索引不同也可。
回文数列要求正序和逆序内容必须一致,所以是中心对称结构。那么我们一共有多少个可能的中心呢?
因为一个元素也可以构成回文数列,那么每个元素自己都可以作为中心。而且,对于偶数个的回文序列,他们的中心位于两个元素之间。所以可能的重心一共有2n-1个。
class Solution(object):
def countSubstrings(self, s):
res = 0
n = len(s)
for i in range(0, n):
res += 1
left = i -1
right = i + 1
while left >= 0 and right < n and s[left] == s[right]:
left -= 1
right += 1
res += 1
left=i
right=i+1
while left>=0 and right <n and s[left] == s[right]:
left-=1
right+=1
res+=1
return res
Reference
https://leetcode.com/problems/palindromic-substrings/discuss/105687/Python-Straightforward-with-Explanation-(Bonus-O(N)-solution)