Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
LeetCode:链接
参考链接:LeetCode647:Palindromic Substrings
647是找出所有的回文字符串,这道题是找到最长的回文字符串,思路都是一样的。
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
if n == 0:
return ""
dp = [[0] * n for i in range(n)]
dp[0][0] = 1
length = 1
result = s[0]
for i in range(1, n):
for j in range(i):
# (i-j < 2)这个最好要封口
dp[j][i] = (s[i] == s[j]) & ((i-j < 2) | dp[j+1][i-1])
if dp[j][i] and (i-j+1) > length:
length = i-j+1
result = s[j:i+1]
dp[i][i] = 1
return result