Skip to content

Instantly share code, notes, and snippets.

@moonwatcher
Created August 15, 2021 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moonwatcher/5dc81ef050ce907204ef14e2842e90a7 to your computer and use it in GitHub Desktop.
Save moonwatcher/5dc81ef050ce907204ef14e2842e90a7 to your computer and use it in GitHub Desktop.
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def check_palindrom(start, end):
while start > 0 and end < n-1 and s[start-1] == s[end+1]:
start-=1
end+=1
length = end - start + 1
if length > longest[2]:
longest[0] = start
longest[1] = end
longest[2] = length
# if no palindrom is found return the first character
# longest is [start, end, length]
longest = [0,0,1]
n = len(s)
# edge cases
if n == 1:
return s[0]
if n == 2:
if s[0] == s[1]:
return s
else:
return s[0]
for i in range(0, n-1):
if s[i] == s[i+1]:
longestPossible = 2 * min(n-i-1, i+1)
if longestPossible > longest[2]:
check_palindrom(i, i+1)
if i > 0 and s[i-1] == s[i+1]:
longestPossible = 2 * min(n-i, i+1) - 1
if longestPossible > longest[2]:
check_palindrom(i-1, i+1)
return s[longest[0]:longest[1]+1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment