5. Longest Palindromic Substring Palindrome Number | LeetCode Using Python
Have you ever wondered how to efficiently find the longest palindromic substring within a given string? Palindromes are sequences that read the same backward as forward, like “radar” or “madam.”
Code in Python:
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
self.longest_palindromic_substring = "" #return output
def expansion(i,j):
#define our conditions
while i >= 0 and j < len(s) and s[i] == s[j]:
if j - i + 1 > len(self.longest_palindromic_substring):
self.longest_palindromic_substring = s[i:j + 1] #update the longest_palindromic_substring
i -= 1
j += 1
#our iteration
for i in range(len(s)):
expansion(i, i) #odd numbered input
expansion(i, i + 1) #for even numbered inputs
#output
return self.longest_palindromic_substring