Leetcode - 5. Longest Palindromic Substring
Coding Test

Leetcode - 5. Longest Palindromic Substring

일시불

답안

브루트 포스 풀이

class Solution:
    def longestPalindrome(self, s: str) -> str:
        s_len = len(s)
        for leng in range(s_len, 0, -1):
            for idx in range(s_len - leng + 1):
                substring = s[idx : idx + leng]
                if substring == substring[::-1]:
                    return substring

Center Expanding 풀이

class Solution:
    def longestPalindrome(self, s: str) -> str:
        def expand(left, right):
            while left >= 0 and right <= len(s) and s[left] == s[right - 1]:
                left -= 1
                right += 1
            return s[left + 1 : right - 1]

        if len(s) < 2 or s == s[::-1]:
            return s

        result = ''
        for i in range(len(s) - 1):
            result = max(result, expand(i, i + 1), expand(i, i + 2), key=len)

        return result