Skip to content

Instantly share code, notes, and snippets.

@pallabpain
Created October 2, 2021 09:29
Show Gist options
  • Save pallabpain/64f801324a5e54bd5d619c1a5d1be4fa to your computer and use it in GitHub Desktop.
Save pallabpain/64f801324a5e54bd5d619c1a5d1be4fa to your computer and use it in GitHub Desktop.
Find the longest palindromic substring
"""
Given a string s, return the longest palindromic substring in s
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
"""
def longestPalindrome(s):
start = 0 # start index of the longest substring
max_length = 1
n = len(s)
for i in xrange(1, n):
# First, look for the longest even palindrome,
# i.e. repeated characters at the centre
l = i-1
h = i
while l >= 0 and h < n and s[l] == s[h]:
if max_length < h - l + 1:
start = l
max_length = h - l + 1
l -= 1
h += 1
l = i-1
h = i+1
while l >= 0 and h < n and s[l] == s[h]:
if max_length < h - l + 1:
start = l
max_length = h - l + 1
l -= 1
h += 1
return s[start:start+max_length]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment