题目描述:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
例子:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
思路:
遍历每一个字符,并以该字符为中心向两边扩散,找到以该字符为中心的最长长度。最后输出最长的情况。
代码:
class Solution:
def longestPalindrome(self, s: str) -> str:
def getLen(l,r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return r - l - 1
start = 0
length = 0
for i in range(len(s)):
cur = max(getLen(i,i),getLen(i,i+1)) #(i,i)是奇数情况,(i,i+1)是偶数情况
if cur <= length: continue
length = cur
start = i - (cur - 1)//2
return s[start:start+length]