Description
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution
class Solution:
def longestPalindrome(self, s: str) -> str:
# 找出以s[l], s[r]为中心的回文串
def Palindrom(l, r):
while l>=0 and r <= len(s)-1 and s[l]==s[r]:
l -= 1
r += 1
return s[l+1:r]
res = ''
# 遍历中心位置
for i in range(len(s)):
res1 = Palindrom(i, i)
res2 = Palindrom(i, i+1)
if len(res1) > len(res): res = res1
if len(res2) > len(res): res = res2
return res
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
self.res = ""
def helper(i,j):
while i >= 0 and j < n and s[i] == s[j]:
i -= 1
j += 1
if len(self.res) < j - i -1 :
self.res = s[i+1:j]
for i in range(n):
helper(i,i)
helper(i,i+1)
return self.res
作者:powcai
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/duo-chong-si-lu-qiu-jie-by-powcai/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。