본문 바로가기
알고리즘/LeetCode

[Python] Longest Palindromic Substring - LeetCode

by Jun Shim 2021. 9. 23.
728x90

5. Longest Palindromic Substring

 

Longest Palindromic Substring - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

2:

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

3:

Input: s = "a"
Output: "a"

4:

Input: s = "ac"
Output: "a"

Constraints:

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

 

Python solution

class Solution:
    def longestPalindrome(self, s: str) -> str:
        if len(s) <= 1:
            return s

        i = l = 0
        for j in range(len(s)):
            if s[j-l: j+1] == s[j-l: j+1][::-1]:
                i = j-l
                l += 1
            elif j-l > 0 and s[j-l-1: j+1] == s[j-l-1: j+1][::-1]:
                i = j-l-1
                l += 2

        return s[i: i+l]

Accepted 104ms runtime

Submission detail

 

728x90

댓글