LeetCode-5、最长回文子串-中等
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
代码1:暴力法
class Solution:
def longestPalindrome(self, s: str) -> str:
ss = ''
if len(s) == 0:
return ss
if len(s) == 1:
return s
dic = {}
lenth = [0]
for ii in range(len(s)):
if s[ii] not in ss:
ss += s[ii]
else:
ind = ss.find(s[ii])
ss += s[ii]
while ind != -1:
str1 = ss[ind:]
if str1 == str1[::-1]:
lenth.append(len(str1))
dic[len(str1)] = str1
ind = ss.find(s[ii],ind+1,-1)
max_len = max(lenth)
if max_len < 1:
return ss[max_len]
else:
return dic[max(lenth)]
处理特殊情况时耗时太久。
代码2:动态规划
class Solution:
def longestPalindrome(self, s: str) -> str:
length = 0
start = 0
for i in range(len(s)):
if i - length >= 1 and s[i - length - 1:i + 2] == s[i - length - 1:i + 2][::-1]:
start = i - length - 1
length += 2
continue
if i - length >= 0 and s[i - length:i + 2] == s[i - length:i + 2][::-1]:
start = i - length
length += 1
return s[start:start + length + 1]