Here's the Python code:
def is_palindrome(s):
return s == s[::-1]
def longestp(s):
if is_palindrome(s):
return s
maxp = s[0]
for i in range(len(s)-1):
half_length = len(maxp) // 2
start = i - half_length
end = i + half_length
while start >= 0 and end <= len(s)-1:
if is_palindrome(s[start:end+2]):
if len(s[start:end+2]) > len(maxp):
maxp = s[start:end+2]
end += 1
elif is_palindrome(s[start:end+1]):
if len(s[start:end+1]) > len(maxp):
maxp = s[start:end+1]
start -= 1
end += 1
else:
break
return maxp
I initially thought it was O(n^3)
because of two nested loops and string slicing, but it turned out to be nearly linear in my tests. Is there any kind of input for which this algorithm is going to be slow?