最长回文子串
Posted Peyton_Li
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最长回文子串相关的知识,希望对你有一定的参考价值。
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
分析:
方法一:暴力求解
遍历字符串,判断以每一个字符为起始的子串是否为回文字符串,记录起始位置和长度。这是最容易想到的方法,但是时间复杂度较大。
方法二:动态规划
p[i][j]表示以第i个字符开始,第j个字符结束的子串是否为回文字符串,p[i][j]=1表示是回文字符串,p[i][j]=0表示不是回文字符串。起始状态p[i][i]=1
转移方程为:p[i][j]=1 if p[i+1][j-1] == 1 and s[i]==s[j] else 0
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
l = len(s)
maxlen = 1
start = 0
p = [[0]*l for i in range(l)]
for i in range(l):
p[i][i]=1
if i < l-1 and s[i] == s[i+1]:
p[i][i+1] = 1
maxlen = 2
start = i
for length in range(3,l+1):
for i in range(l-length+1):
j = i + length -1
if p[i+1][j-1]==1 and s[i] == s[j]:
p[i][j] = 1
maxlen = length
start = i
return s[start:start+maxlen]
以上是关于最长回文子串的主要内容,如果未能解决你的问题,请参考以下文章