题目:
给定一个字符串 s
,找到 s
中最长的回文子串。你可以假设 s
的最大长度为 1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd" 输出: "bb"
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-palindromic-substring/
方法一:
暴力搜索(end = max(start, max_end))
class Solution:
def longestPalindrome(self, s: str) -> str:
l = len(s)
if l==0:
return ''
max_length = 0
start = 0
max_end = 0
result = ''
for start in range(l):
end = max(start, max_end)
while(end<=l):
end+=1
if self.isPalindrome(s[start:end]):
if end-start>max_length:
max_length=end-start
result = s[start:end]
if end>max_end:
max_end = end
return result
def isPalindrome(self, s):
s1 = s[::-1]
if s == s1:
return True
else:
return False
方法二:
动态规划:找出字符串中长度为1,2,3....n的回文子串。
dp[i][j] = dp[i+1][j-1] and s[i]==s[j]
class Solution:
def longestPalindrome(self, s: str) -> str:
l = len(s)
if l<=1:
return s
dp = [[0]*(l+1) for i in range(l+1)]
for length in range(l+1):
T = 0
for i in range(l-length+1):
j = i+length
if j>l:
break
if length<=1:
dp[i][j] = 1
if T==0:
result = s[i:j]
T = 1
else:
if dp[i+1][j-1]==1 and s[i]==s[j-1]:
dp[i][j] = 1
if T==0:
result = s[i:j]
T = 1
else:
dp[i][j] = 0
return result
方法三:
中心扩展算法
思路:1.首先判断输入字符串为空的情况;
2.遍历整个字符串,以当前遍历位置的字符为中心,进行扩展。
(注意回文子串的中心有两种情况,一是回文子串长度为奇数,中心为单个字符;二是子串长度为偶数,中心为双字符)
class Solution:
def longestPalindrome(self, s: str) -> str:
l = len(s)
head = 0
tail = 0
result = ''
if l == 0:
return result
result = s[0]
length = 1
for i in range(l):
head = i - 1
tail = i
while True:
if head < 0 or tail == l:
break
if s[head] == s[tail]:
head = head - 1
tail = tail + 1
else:
break
length_sub = tail - head - 1
if length_sub > length:
length = length_sub
result = s[head + 1:tail]
head = i - 1
tail = i + 1
while True:
if head < 0 or tail == l:
break
if s[head] == s[tail]:
head = head - 1
tail = tail + 1
else:
break
length_sub = tail - head - 1
if length_sub > length:
length = length_sub
result = s[head + 1:tail]
return result