class Solution:
# @return a string
def longestPalindrome(self, s):
n=len(s)
inputstr=s
s=list(s)
i=0
L=2*n+1
#insert '#' into the string so that the even and odd palidrome are the same
while i<L:
s.insert(i,'#')
i+=2
right=0
P=[0]*L
mid=0
for i in range(1,L):
if i<right:
mirror=2*mid-i
if i+P[mirror]<right:
P[i]=P[mirror]
continue
else:
P[i]=right-i
j=P[i]+1
while 0<=i-j and i+j<L and s[i-j]==s[i+j]:
P[i]+=1
j+=1
mid=i
right=mid+P[i]
index,maxlen=max(enumerate(P),key=operator.itemgetter(1))
seq=int(index//2-P[index]// 2)
rst=inputstr[seq:seq+P[index]]
return rst
Thursday, September 18, 2014
Leetcode: Longest Palindromic Substring @Python
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment