DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1

Longest Palindromic Substring

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"

Constraints:

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

SOLUTION:

class Solution:
    def strech(self, s, i, j, n):
        l = 0
        while i - l >= 0 and j + l < n and s[i - l] == s[j + l]:
            l += 1
        l -= 1
        return (i - l, j + l)

    def longestPalindrome(self, s) -> str:
        n = len(s)
        mx, my = 0, 0
        for i in range(n - 1):
            for a, b in [(i, i), (i, i + 1)]:
                x, y = self.strech(s, a, b, n)
                if y - x > my - mx:
                    mx, my = x, y
        return s[mx:my+1]
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay