234. Palindrome Linked List Python3

Yelim Kim·2021년 9월 18일
0

Python Algorithm Interview

목록 보기
12/36
post-thumbnail

Problem

Given the head of a singly linked list, return true if it is a palindrome.

Example 1:

Input: head = [1,2,2,1]
Output: true

Example 2:

Input: head = [1,2]
Output: false

Constraints:

The number of nodes in the list is in the range [1, 105].
0 <= Node.val <= 9

My code

class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        n_head = getNodesInArray(head)
        string = ''.join(str(_) for _ in n_head)
        if string != string[::-1]:
            return False
        else :
            return True

def getNodesInArray(self):
    nodes = []
    current = self
    while current is not None:
        nodes.append(current.val)
        current = current.next
    return nodes

Review

[실행 결과]
Runtime: 914 ms / Memory : 47.4MB

[접근법]
저번에 적었던 코드를 써먹자 해서 연결 리스트를 문자열로 변환해주는 함수를 만들고 변환해준 후 써먹었다.
맨 처음문자부터 뒤로 하나씩 = 맨 뒤에서부터 앞으로 하나씩 비교하면서 틀리면 바로 False

[느낀점]
정수형 리스트일때는 반드시 ''.join(str() for in n_head)로 적어서 바꿔주기!

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글