Leetcode5. 最长回文子串

Leetcode链接

动态规划代码

class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = ""
# 枚举子串的长度 l+1
for l in range(n):
# 枚举子串的起始位置 i，这样可以通过 j=i+l 得到子串的结束位置
for i in range(n):
j = i + l
if j >= len(s):
break
if l == 0:
dp[i][j] = True
elif l == 1:
dp[i][j] = (s[i] == s[j])
else:
dp[i][j] = (dp[i + 1][j - 1] and s[i] == s[j])
if dp[i][j] and l + 1 > len(ans):
ans = s[i:j+1]
return ans

class Solution:
def expandAroundCenter(self, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return left + 1, right - 1

def longestPalindrome(self, s: str) -> str:
start, end = 0, 0
for i in range(len(s)):
left1, right1 = self.expandAroundCenter(s, i, i)
left2, right2 = self.expandAroundCenter(s, i, i + 1)
if right1 - left1 > end - start:
start, end = left1, right1
if right2 - left2 > end - start:
start, end = left2, right2
return s[start: end + 1]

11-13 2万+

05-23 1451

01-06 536

01-27 251

08-29 2万+

07-11 285

08-12 134

07-15 2196

05-15 2018

09-13 282

03-08 1546

11-23 118

07-01 2120

05-21 280

05-10 201

09-06 199

05-15 305

04-17 972

12-10 200

03-03 126

LeetCode题解(python)-5. 最长回文子串

©️2019 CSDN 皮肤主题: 护眼 设计师: 闪电赇