Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$


Solution

# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    # ์‹œ๊ฐ„ ๋ณต์žก๋„: O(N)
    # Runtime: 754ms
    # Beats: 83.59%
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        # ์ฒ˜์Œ์— head๊ฐ€ null์ธ ๊ฐ’๋„ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค˜์•ผ ํ•˜๋Š” ์ค„ ์•Œ์•˜์—ˆ์ง€๋งŒ
        # ์˜คํžˆ๋ ค ์†๋„๋งŒ ๋Šฆ์ถœ ๋ฟ ํ•„์š”๊ฐ€ ์—†์—ˆ์Œ
        # Optional๋กœ ๊ฐ์‹ธ์„œ ๋“ค์–ด์˜ค๋‹ˆ ๋‹น์—ฐํžˆ ํ•„์š”๊ฐ€ ์—†์ง€

        array = []
        current = head

        # linkedList์˜ ๋ชจ๋“  ๊ฐ’์„ array ๋ฐฐ์—ด์— ์ˆœ์ฐจ์ ์œผ๋กœ ์ €์žฅ
        # current (head)๊ฐ€ null์ด ์•„๋‹ ๋•Œ ๋ฐ˜๋ณต๋ฌธ ๋Œ์•„์ฃผ์ž
        while current is not None:
            # ๋ฐฐ์—ด์— ๊ณ„์† ์ถ”๊ฐ€ํ•ด์ฃผ๊ณ 
            array.append(current.val)
            # ๋…ธ๋“œ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™์‹œ์ผœ์ฃผ๊ธฐ
            current = current.next

        # [::-1] -> ๋ฐฐ์—ด ๋’ค์ง‘๊ธฐ
        # ๊ทธ๋ƒฅ ๋ฐฐ์—ด๊ณผ ๊ทธ ๋’ค์ง‘์€ ๋ฐฐ์—ด์ด ๋™์ผํ•˜๋ฉด true๋ฅผ ๋ฆฌํ„ดํ•˜๊ฒŒ๋”
        return array == array[::-1]

Leave a comment