题目链接:
https://leetcode.com/problems/longest-palindromic-substring/
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
解法一:
利用Array[i][j] 表示s[i]到s[j]为回文字串,利用动态规划的方式来求解以寻找到最长的回文子串。
class Solution:
# @return a string
def longestPalindrome(self, s):
Array = []
Temp = [0]*len(s)
Temp[0] = 1
Array.append(Temp)
for i in range(1,len(s)):
Temp = [0]*len(s)
Temp[i-1] = 1
Temp[i] = 1
Array.append(Temp)
Max = 0
start = 0
for j in range(1,len(s)):
for i in range(0,j):
if s[i] == s[j]:
Array[i][j] = Array[i+1][j-1]
if Array[i][j] and Max < j-i+1:
Max = j-i+1
start = i
else:
Array[i][j] = 0
return s[start:start+Max]<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"> </span>
结果:
Time Limit Exceeded
原因:使用列表,耗时。
解法二:
学习了一种新的算法来处理字符串回文:Manacher's Algorithm
http://blog.csdn.net/pi9nc/article/details/9251455
http://www.felix021.com/blog/read.php?2040
时间复杂度为O(n)
耗时:151ms