Skip to content

Commit

Permalink
[python]longest-palindromic-substring
Browse files Browse the repository at this point in the history
  • Loading branch information
Huauauaa committed Aug 24, 2024
1 parent dd2b1a7 commit 4009964
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/leetcode/00005.longest-palindromic-substring/5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
if n < 2:
return s

max_len = 1
begin = 0
# dp[i][j] 表示 s[i..j] 是否是回文串
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True

# 递推开始
# 先枚举子串长度
for L in range(2, n + 1):
# 枚举左边界,左边界的上限设置可以宽松一些
for i in range(n):
# 由 L 和 i 可以确定右边界,即 j - i + 1 = L 得
j = L + i - 1
# 如果右边界越界,就可以退出当前循环
if j >= n:
break

if s[i] != s[j]:
dp[i][j] = False
else:
if j - i < 3:
dp[i][j] = True
else:
dp[i][j] = dp[i + 1][j - 1]

# 只要 dp[i][L] == true 成立,就表示子串 s[i..L] 是回文,此时记录回文长度和起始位置
if dp[i][j] and j - i + 1 > max_len:
max_len = j - i + 1
begin = i
return s[begin : begin + max_len]

0 comments on commit 4009964

Please sign in to comment.