From 40099647a18b208712d05cb313620e1738105b69 Mon Sep 17 00:00:00 2001 From: Harvey Date: Sat, 24 Aug 2024 15:12:58 +0800 Subject: [PATCH] [python]longest-palindromic-substring --- .../00005.longest-palindromic-substring/5.py | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/leetcode/00005.longest-palindromic-substring/5.py diff --git a/src/leetcode/00005.longest-palindromic-substring/5.py b/src/leetcode/00005.longest-palindromic-substring/5.py new file mode 100644 index 0000000..32151fb --- /dev/null +++ b/src/leetcode/00005.longest-palindromic-substring/5.py @@ -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]