1.题目
2. 考点
- 双指针
- 中心扩散
- 回文串 例如:noon aba等 A[l:r] == A[l:r][::-1]
3. 解析
使用双指针
4. 核心代码
双指针解法
class Solution:
def getLongestPalindrome(self , A: str) -> int:
n = len(A)
if n == 1: return 1
l = 0
r = 1
ret = 0
while l <= r <= n:
while r <= n:
if A[l:r] == A[l:r][::-1]:
ret = max(ret, r - l)
r += 1
l += 1
r = l + 1
return ret
中心扩散法
class Solution:
def fun(self, s: str, begin: int, end: int) -> int:
#每个中心点开始扩展
while begin >= 0 and end < len(s) and s[begin] == s[end]:
begin -= 1
end += 1
#返回长度
return end - begin - 1
def getLongestPalindrome(self , A: str) -> int:
maxlen = 1
#以每个点为中心
for i in range(len(A) - 1):
#分奇数长度和偶数长度向两边扩展
maxlen = max(maxlen, max(self.fun(A, i, i), self.fun(A, i, i + 1)))
return maxlen
4. 代码优化
# 如需要返回长度 只需要返回len就可以了
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return ""
if s[::-1] == s:
return s
n = len(s)
left = 1
temps = s[0]
for i in range(n):
if i - left >= 1 and s[i - left - 1:i + 1] == s[i - left - 1:i + 1][::-1]:
temps = s[i - left - 1:i + 1]
left += 2
elif i - left >= 0 and s[i - left:i + 1] == s[i - left:i + 1][::-1]:
temps = s[i - left:i + 1]
left += 1
return temps
5. 很好理解法
采用中心扩散 如果为奇数就为 _is_palindrome(s, i, i) 如果是偶数_is_palindrome(s, i, i + 1) 最后获取最长的那个结果
class Solution:
def longestPalindrome(self, s: str) -> str:
def _is_palindrome(ss, l, r):
while l >= 0 and r < len(ss) and ss[l] == ss[r]:
l -= 1
r += 1
return ss[l + 1: r]
res = ""
for i in range(len(s)):
s1 = _is_palindrome(s, i, i)
s2 = _is_palindrome(s, i, i + 1)
res = s1 if len(s1) > len(res) else res
res = s2 if len(s2) > len(res) else res
return res