Python3最长回文子串算法示例

yipeiwu_com6年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

用实例分析Python中method的参数传递过程

什么是method? function就是可以通过名字可以调用的一段代码,我们可以传参数进去,得到返回值。所有的参数都是明确的传递过去的。 method是function与对象的结合。我...

利用pyshp包给shapefile文件添加字段的实例

在已有的shapefile文件的基础上增加字段: # -*- coding:gb2312 -*- import shapefile r=shapefile.Reader(r"C:...

Python字符串拼接、截取及替换方法总结分析

本文实例讲述了Python字符串拼接、截取及替换方法。分享给大家供大家参考,具体如下: python字符串连接 python字符串连接有几种方法,我开始用的第一个方法效率是最低的,后来看...

unittest+coverage单元测试代码覆盖操作实例详解

unittest+coverage单元测试代码覆盖操作实例详解

基于上一篇文章,这篇文章是关于使用coverage来实现代码覆盖的操作实例,源代码在上一篇已经给出相应链接。 本篇文章字用来实现代码覆盖的源代码,整个项目的测试框架如下: 就是在源代码...

python3正则提取字符串里的中文实例

python3正则提取字符串里的中文实例

如下所示: # -*- coding: utf-8 -*- import re #过滤掉除了中文以外的字符 str = "hello,world!!%[545]你好234世界。。。"...