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.
Example 1:
Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
题目的意思就是找到所给字符串中所有的回环序列个数,首先明确的是需要有两个指针,若从头开始遍历,时间复杂度为n(o^2),所以考虑动态规划,采用中心扩张的方法,长度为n的字符串有2*n-1个回环中心,将回环中心依次编号,设立left和right两个指针,从回环中心开始,依次向外扩张,若s[left]==s[right]且left和right在0到n的范围内咋回环个数加一并继续向外扩张,直到不满足条件,难点在于初始指针的确定。
如果回环中心在第i个字符上,则,left=right=i,此时回环中心为2*i,若回环中心在字符i,j之间,left=i,right=i+1,回环中心为2*i+1,所以当回环中心在center(第center个回环中心)时left=center/2,而right=center/2+center%2
故代码如下
def countSubstrings(self, S):
N = len(S)
ans = 0
for center in xrange(2*N - 1):
left = center / 2
right = left + center %2
while left >= 0and right <N and S[left] == S[right]:
ans += 1
left -=1
right +=1
return ans
练习:413