Skip to content

Instantly share code, notes, and snippets.

@hristo-vrigazov
Last active December 7, 2016 15:17
Show Gist options
  • Save hristo-vrigazov/4cc750960c39e41b1cbb6b54b11a4151 to your computer and use it in GitHub Desktop.
Save hristo-vrigazov/4cc750960c39e41b1cbb6b54b11a4151 to your computer and use it in GitHub Desktop.
Longest palindromic substring in quadratic time O(n^2)
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
best_palindrome_length = 1
best_palindrome = s[0]
n = len(s)
for i in range(2 * n - 1):
if i % 2 == 0:
candidate_string = s[i/2]
left = i / 2 - 1
right = i / 2 + 1
else:
candidate_string = ''
left = i / 2
right = i / 2 + 1
while left >= 0 and right < n and s[left] == s[right]:
candidate_string = s[left] + candidate_string + s[right]
left -= 1
right += 1
if len(candidate_string) > best_palindrome_length:
best_palindrome = candidate_string
best_palindrome_length = len(candidate_string)
return best_palindrome
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment