Published:
Updated:

  • Reference
  • ํˆฌํฌ์ธํ„ฐ์ธ ๊ฒƒ์€ ์ง๊ฐํ–ˆ์ง€๋งŒ ์ด๋ ‡๊ฒŒ ์–ด๋ ค์šธ ์ค„์€ ๋ชฐ๋ž๋‹ค.


Solution

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

        # ํŒฐ๋ฆฐ๋“œ๋กฌ ํŒ๋ณ„ ๋ฐ ํˆฌํฌ์ธํ„ฐ ํ™•์žฅ
        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]

        # ์Šฌ๋ผ์ด์‹ฑ ์šฐ์ธก์œผ๋กœ ์ด๋™
        result = ''
        for i in range(len(s) - 1):
            # expand ๊ฐ๊ฐ ํ™€์ˆ˜, ์ง์ˆ˜
            result = max(result, expand(i, i + 1), expand(i, i + 2), key=len)

        return result

Leave a comment