LeetCode 5 - Longest Palindromic Substring Problem

Problem Statement

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

Solution:

class Solution: def longestPalindrome(self, s: str) -> str: if not s: return '' max_palindrome = '' for i in range(len(s)): oddPalindrome = self.palindrome(s, i, i) evenPalindrome = self.palindrome(s, i, i+1) if len(oddPalindrome)>len(evenPalindrome): current_palindrome = oddPalindrome else: current_palindrome = evenPalindrome if len(max_palindrome) < len(current_palindrome): max_palindrome = current_palindrome return max_palindrome def palindrome(self, s, start, end): left=right=0 while start>=0 and end<len(s) and s[start]==s[end]: left = start right = end start-=1 end+=1 return s[left:right+1]