题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
判断回文,首先要理解什么是回文,会稳定定义是什么,详解里面说的很清楚。
# -*- coding:utf-8 -*- class Solution: def getLongestPalindrome(self, A, n): # print([False] * n) # write code here if n < 2:return len(A) maxlen = 1 dp = [[False] * n for _ in range(n)] //定义n*n矩阵,这里有大坑 for i in range(n): dp[i][i] = True for right in range(n): for left in range(right): if A[left] != A[right]://如果两种字符不相等,肯定不是回文 continue if right == left://默认相等的情况 dp[left][right] = True elif right - left <= 2://类似aa这种也是回文子串 dp[left][right] = True else: dp[left][right] = dp[left + 1][right - 1]//判断是否是回文子串 if dp[left][right] and right - left + 1 > maxlen://计算最大回文的长度 maxlen = right - left + 1 return maxlen