给定字符串s,找到s中最长的回文子字符串。您可以假设s的最大长度为1000。
Input | Output |
---|---|
"" | "" |
"abc" | "a" |
"ababc" | "bab" |
Method 1 建立两个循环, 遍历每个子字符串判断是否为palindromic
1. 如果字符串为空则需要返回空
2. 如果字符串没有回文,则需要返回第一个字母
3. 如果后面的palindromic substring比之前的长度长, 需要替换掉之前的
判断是否为回文用125题的方法, 将字符串逆序, 判断是否一样
class Solution:
def longestPalindrome(self, s: str) -> str:
l=len(s)
if l==0:
return s
max_len=0
for i in range(l):
temp=s[i]
for j in range(i+1,l):
temp+=s[j]
if temp==temp[::-1]:
max_len=max(max_len,len(temp))
if max_len==len(temp):
res=temp
if max_len==0:
return s[0]
else:
return res
时间复杂度: O(n²)因为两层循环
Method 2 以每个字符串为中心,判断左右字符串是否相等2.0
1. 用特殊符号填充s并定义为临时字符串t,让s中的字母落在偶数位置。为了防止以字符串为中心时,‘abba’这种情况中心在两个字符之间。
{t='>#'+'#'join.(s)+'#<'}
2. 定义一个中心c,和半径r,用来判断以c位置为中心的t[c+r]到t[c-r]是否回文
{c=t=0}
3. 遍历t中的字符串,如果遍历到‘#’时,那么就从其前后1个位置开始判断是否回文,如果遍历到字母时就从其前后两个位置开始判断是否回文
{for i in range(1, len(t)-1):
j=1 if t[i]=='#' else 2
while t[i-j]==t[i+j]: j+=2}
4. 当j大于当前半径时,把i的值赋给c,j的值赋给r
{if j>r: c,r=i,j}
5. 返回c,r相对于s中的字符串,因为会有‘aab’这种对称在两个数之间的,并且开头结尾多加了一个'>''<' ,所以开头要+1除2取整,结尾要-1除2取整
{return s[(c-r+1)//2: (c+r-1)//2]}
i | t[i] | j | t[i-j]==t[i+j], j+=2 | j>r | c | r |
---|---|---|---|---|---|---|
1 | # | 1 | >!=a | j=1 r=0--T | 1 | 1 |
2 | a | 2 | >!=a | j=2 r=1--T | 2 | 2 |
3 | # | 1 | a==a, >!=b | j=3 r=2--T | 3 | 3 |
4 | a | 2 | a!=b | j=2 r=3--F | 3 | 3 |
5 | # | 1 | a!=b | j=1 r=3--F | 3 | 3 |
6 | b | 2 | a!=< | j=2 r=3--F | 3 | 3 |
7 | # | 1 | b!=< | j=1 r=3--F | 3 | 3 |
对应t的字符t[3-3+1:3+3-1]-->'#a#a#'
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s)<2 or s==s[::-1]:
return s
t='>#'+'#'.join(s)+'#<'
c=r=0
for i in range(1,len(t)-1): #因为第一位和最后一位是>和<
if t[i]=='#': #j=1 if t[i]=='#' else 2
j=1
else:
j=2
while t[i-j]==t[i+j]:
j+=2
if j>r:
c,r=i,j
return s[(c-r+1)//2:(c+r-1)//2]
时间复杂度O(n)