题目链接:https://leetcode.com/problems/longest-palindromic-substring/
代码:
class Solution:
def longestPalindrome(self, s: str) -> str:
def helper(i, j):
while i >=0 and j < len(s) and s[i]==s[j]:
i,j=i-1,j+1
return s[i+1:j] # s[i] != s[j],返回回文串
return s and max((a for i in range(len(s))
for a in (helper(i, i), helper(i, i+1))), key=len) or ''
思路详解
基本思路:以点为中心,向两边进行查找,直到s[i] != s[j],那么返回中间的回文字符
- 单点为中心
- 双点为中心
比较点单和双点的回文串,返回最长的串即为所求
注意点
- 空值情况返回空
- 中心需要分单点和双点情况