Leetcode - Longest Palindromic Substring Solution
1 min read

Leetcode - Longest Palindromic Substring Solution

Given a string s, return the longest palindromic substring in s.

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"
Output: "bb"


  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

Solution in Python3

class Solution:
    def longestPalindrome(self, s: str) -> str:
        if len(s)==1:
            return s
        def createCenter(s,mid):
            yield mid
            for i in range(1,mid+1):
                yield mid-i
                if mid+i == len(s):
                yield mid+i
        def longestPalin(s,index):
            i = index-1
            j = index+1
            while i>-1 and j<len(s) and s[i]==s[j]:
            return s[i+1:j]

        def longestPalinDual(s,i,j):
            while i>-1 and j<len(s) and s[i]==s[j]:
            return s[i+1:j]

        mid = len(s)//2
        longest = ""
        for center in createCenter(s,mid):
            l = center
            r = len(s) - center - 1
            lp = min(l,r)*2+1
            pal = longestPalin(s,center)
            if len(pal)>len(longest):
                longest = pal
            if lp<=len(longest):
        # DUAL
        centers = []
        for i in range(1,mid+1):
        # DUAL
        if centers[-1][-1]==len(s):
        # DUAL
        longest_dual = ""
        for center in centers:
            x,y = center
            l = x
            r = len(s) - y - 1
            lp = min(l,r)*2+2
            if s[x] == s[y]:
                pal = longestPalinDual(s,x,y)
                if len(pal)>len(longest_dual):
                    longest_dual = pal
                if lp<=len(longest_dual):
        if len(longest)>len(longest_dual):
            return longest
            return longest_dual

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.