给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd"
输出:"bb"
示例 3:
输入:s = "a"
输出:"a"
示例 4:
输入:s = "ac"
输出:"a"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
大神题解
class Solution(object):
def longestPalindrome(self, s):
if len(s) <= 1:
return s
dp = [0] * len(s)
dp[0] = 1
for i in range(1, len(dp)):
if i-1-dp[i-1] >= 0 and s[i] == s[i-1-dp[i-1]]:
dp[i] = dp[i-1]+2
else:
dp[i] = 1
for j in range(i-1-dp[i-1]+1, i):
if s[j:i+1] == s[j:i+1][::-1]:
dp[i] = i-j+1
break
max_len = 0
max_id = 0
for i in range(len(dp)):
if dp[i] > max_len:
max_id = i
max_len = dp[i]
return s[max_id-max_len+1:max_id+1]
超时题解
class Solution:
def longestPalindrome(self, s: str) -> str:
hui_max=0
re_hui=""
head_index=0
if self.huiwen(s):
return s
else:
for _ in s:
hu = ""
for i in s[head_index:]:
hu+=i
if self.huiwen(hu):
if len(hu)>hui_max:
hui_max=len(hu)
re_hui=hu
head_index+=1
print(re_hui)
return re_hui
def huiwen(self, s):
if "".join(reversed([i for i in s])) == s:
return True
else:
return False