我们提供两种思路:
1、更为直观的“中心向外扩散法”
因为回文串 要么是形如“…xx…”
要么是形如“…xax…”
因此我们首先遍历一遍字符串s,找到所有符合
a[i] == a[i+1] 的i 记录到list1 中
再找所有符合
a[i-1] == a[i+1]的i,记录到list2中
然后 对list1 和list2 中 的 i 我们分别从该处开始 安排两个指针 向两边扩散
终止条件为 要么是出了边界 要么是两个指针指向的值不再相等
最后保留最长的
代码:
class Solution:
def __init__(self):
self.res = ''
self.maxlen = 0
def longestPalindrome(self, s: str) -> str:
if s == '':
return ''
length = len(s)
#if length <= 1
dl = []#'...bb...'
tl = []#'...sbs...'
#当然,如果优化一下的话,我们可以只用一个list存储,然后下面在tempres的初始化时分情况
for i in range(length - 1):
if s[i] == s[i+1]:
dl.append(i)
if i > 0 and s[i-1] == s [i+1]:
tl.append(i)
for loc in dl:
cur1 = loc
cur2 = loc + 1
tempres = ''#s[cur1] + s[cur2]
templen = 0
while cur1 >= 0 and cur2 < length and s[cur1] == s[cur2]:
tempres = s[cur1] + tempres + s[cur2]
templen += 2
cur1 -= 1
cur2 += 1
if templen > self.maxlen:
self.res = tempres
self.maxlen = templen
for loc in tl:
cur1 = loc - 1
cur2 = loc + 1
tempres = s[loc]
templen = 1
while cur1 >= 0 and cur2 < length and s[cur1] == s[cur2]:
tempres = s[cur1] + tempres + s[cur2]
templen += 2
cur1 -= 1
cur2 += 1
if templen > self.maxlen:
self.res = tempres
self.maxlen = templen
return self.res if self.res != '' else s[0]
2、动态规划
对于串的动态规划
我们要在定义子问题时注意经验
在本题中
dp[i][j]的含义是 以s[i]开头以s[j]结尾的最长回文字串的长度
则
dp[i][i] = 1
dp[i][i+1] = 2 if s[i] == s[i+index] else 0
dp[i][j] = 2 + dp[i+1][j-1] if (s[i] == s[j]) and (dp[i+1][j-1]>0) else 0
class Solution:
def __init__(self):
self.res = ''
self.maxlen = 0
def longestPalindrome(self, s: str) -> str:
if s == '':
return ''
length = len(s)
dp = []
for _ in range(length):
dp.append([None for _ in range(length)])
index = 0
maxa = 1
tempres = ''
while index < length:
for i in range(length-index):
if index == 0:
dp[i][i] = 1
elif index == 1:
dp[i][i+index] = 2 if s[i] == s[i+index] else 0
if maxa == 1 and dp[i][i+index] == 2:
tempres = s[i:i+index+1]
maxa = 2
else:
dp[i][i+index] = 2 + dp[i+1][i+index-1] if (s[i] == s[i+index]) and (dp[i+1][i+index-1]>0) else 0
if dp[i][i+index] > maxa:
tempres = s[i:i+index+1]
maxa = dp[i][i+index]
index += 1
return tempres if tempres != '' else s[0]