最长回文子序列 python_Python3最长回文子串算法示例

本文实例讲述了Python3最长回文子串算法。分享给大家供大家参考,具体如下:

1. 暴力法

思路:对每一个子串判断是否回文

class Solution:

def longestPalindrome(self, s):

"""

:type s: str

:rtype: str

"""

if len(s) == 1:

return s

re = s[0]

for i in range(0,len(s)-1):

for j in range(i+1,len(s)):

sta = i

end = j

flag = True

while sta < end:

if s[sta] != s[end]:

flag = False

break

sta += 1

end -= 1

if flag and j-i+1 > len(re):

re = s[i:j+1]

return re

提交结果:超出时间限制

2. 动态规划法

思路:

m[i][j]标记从第i个字符到第j个字符构成的子串是否回文,若回文值为True,否则为False.

初始状态 s[i][i] == True,其余值为False.

当 s[i] == s[j]  and m[i+1][j-1] == True 时,m[i][j] = True

class Solution:

def longestPalindrome(self, s):

"""

:type s: str

:rtype: str

"""

k = len(s)

matrix = [[False for i in range(k)] for j in range(k)]

re = s[0:1]

for i in range(k):

for j in range(k):

if i==j:

matrix[i][j] = True

for t in range(1,len(s)): #分别考虑长度为2~len-1的子串(长串依赖短串的二维数组值)

for i in range(k):

j = i+t

if j >= k:

break

if i+1 <= j-1 and matrix[i+1][j-1]==True and s[i] == s[j]:

matrix[i][j] = True

if t+1 > len(re):

re = s[i:j+1]

elif i+1 == j and j-1 == i and s[i] == s[j]:

matrix[i][j] = True

if t+1 > len(re):

re = s[i:j+1]

return re

执行用时:8612 ms

希望本文所述对大家Python程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值