5. 最长回文子串python
时间: 2023-11-09 11:56:35 浏览: 189
python 实现最长回文子串
回答: 最长回文子串可以通过两种方法来实现。第一种是使用中心扩展法,代码如下:
```python
class Solution:
def check(self, s, l, r):
while l >= 0 and r < len(s) and s[l == s[r]:
l -= 1
r += 1
return l + 1, r - 1
def longestPalindrome(self, s: str) -> str:
start, end = 0, 0
for x in range(len(s)):
l1, r1 = self.check(s, x, x)
l2, r2 = self.check(s, x, x + 1)
if r1 - l1 > end - start:
start, end = l1, r1
if r2 - l2 > end - start:
start, end = l2, r2
return s[start:end+1]
```
第二种方法是使用动态规划,代码如下:
```python
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ''
for i in range(len(s)):
start = max(0, i - len(res) - 1)
temp = s[start:i+1]
if temp == temp[::-1]:
res = temp
else:
temp = temp<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [5. 最长回文子串(Python 实现)](https://blog.csdn.net/d_l_w_d_l_w/article/details/118861851)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [LeetCode(Python3)5.最长回文子串](https://blog.csdn.net/weixin_52593484/article/details/124718655)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [力扣 (LeetCode)刷题笔记5.最长回文子串 python](https://blog.csdn.net/qq_44672855/article/details/115339324)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文