[Leet Code - String] 5. Longest Palindromic Substring
题目来源
题意分析
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
解题思路
显而易见该题的解题方法在于遍历,但是问题的关键在于如何遍历。考虑如下事实:回文串都有一个“中心”,长度为奇数的回文串中心是一个字符,长度为偶数的回文串中心是两个相同的字符。于是考虑对这个“中心”进行遍历,每次根据该中心对回文串进行扩充,找出对应的最长回文串,最后取所有回文子串中最大的即得到最终结果。该算法的复杂度为O(n^2)
答题源码
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
max_str = ""
max_len = 0
i = 0
for i in range(0, len(s)):
# 奇数回文串
j = 0
while i + j < len(s) and i - j >= 0:
if s[i + j] != s[i - j]:
break
j += 1
if 2 * j - 1 > max_len:
max_len = 2 * j - 1
max_str = s[i-j+1:i+j]
# 偶数回文串
j = 0
while i + j + 1 < len(s) and i - j >= 0:
if s[i + j + 1] != s[i - j]:
break
j += 1
if 2 * j > max_len:
max_len = 2 * j
max_str = s[i - j + 1:i + j + 1]
return max_str