最长回文子串的python实现
看到题目自己的第一反应是中心扩展法,实现功能后发现还有动态规划,码出来后发现还有一维动态规划和马拉车(Manacher)。。。。有空再研究了
中心扩展
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
if length == 0:
return ''
newstr1 = [1] * length
newstrlength1 = [1] * length
for i in range(length):#奇数回文串
k = min(i, length-1 - i)+1
x = 0
y = 1
for j in range(k):
m = i - j
n = i + j
if s[m] != s[n]:
x=1
y=0
break #终止循环意味着回文串头尾已不同,将取值往中间各移动一位
newstr1[i] = s[m+x:n+y]
newstrlength1[i] = len(newstr1[i])
if length==1:
newstr2=s[i]
newstrlength2=[1]
else:
newstr2 = [1] * (length-1)
newstrlength2 = [1] * (length-1)
for i in range(length-1):#偶数回文串
k = min(i, length-2 - i)+1
x = 0
y = 1
for j in range(k):
m = i - j
n = i + j + 1
if s[m] != s[n]:
x=1
y=0
break #终止循环意味着回文串头尾已不同,将取值往中间各移动一位
newstr2[i] = s[m+x:n+y]
newstrlength2[i] = len(newstr2[i])
k1 = newstrlength1.index(max(newstrlength1))
k2 = newstrlength2.index(max(newstrlength2))
if max(newstrlength1)>=max(newstrlength2):
return(newstr1[k1])
else:
return(newstr2[k2])
二维动态规划
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
if length == 0:
return ''
else:
temp = s[0]
table=[['false' for i in range(length)] for j in range(length)]
for i in range(length):# length == 1
table[i][i]='true'
for i in range(length-1):# if length==2
if s[i]==s[i+1]:
table[i][i+1]='true'
if len(temp)<len(s[i:i+2]):
temp=s[i:i+2]
for slen in range(3,length+1):# if length>=3
for i in range(length-slen+1):
if s[i]==s[slen+i-1] and table[i+1][slen+i-2]=='true':
table[i][slen+i-1] = 'true'
if len(temp)<len(s[i:slen+i]):
temp=s[i:slen+i]
return temp
有兴趣可以看这里的总结,很到位。
https://writings.sh/post/algorithm-longest-palindromic-substring