python-algorithm

leetcode 5. Longest Palindromic Substring

무적김두칠 2023. 2. 8. 16:06

https://leetcode.com/problems/longest-palindromic-substring/description/

 

Longest Palindromic Substring - LeetCode

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.le

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def longestPalindrome(self, s: str-> str:
        def expand(left: int, right: int-> str:
            while left >= 0 and right < len(s) and s[left] == s[right]:
                left -= 1
                right += 1
            return s[left + 1:right]
 
        if len(s) < 2 or s == s[::-1]:
            return s
 
        result = ''
 
        for i in range(0len(s) - 1):
            result = max(result,
                         expand(i, i + 1),
                         expand(i, i + 2),
                         key=len)
 
        return result
cs
반응형