Longest Palindromic Substring
Posted 你瞅啥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
题目如下:
此题用Manacher算法求解,时间复杂度为O(n)
Python代码:
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ s = "#" + "#".join(s) + "#" print s i = 0 mx = 0 id = 0 p = [0 ] * len(s) while i<len(s): if mx > i: p[i] = min(p[ 2*id-i],mx-i) else: p[i] = 1 while i-p[i] >=0 and i+p[i] < len(s) and s[i-p[i]]==s[i+p[i]]: p[i] += 1 if mx < p[i]+i: mx = p[i] + i id = i i+=1 middle = p.index(max(p)) start = middle-(max(p)-2) end = middle+(max(p)-2)+1 rstr = \'\' for i in range(start,end,2): rstr += s[i] return rstr
以上是关于Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
5. Longest Palindromic Substring
[Leetcode]Longest Palindromic Substring
LeetCode:Longest Palindromic Substring