문제 링크 : https://leetcode.com/problems/palindrome-linked-list/
연결 리스트(Linked List) 가 palindrome(=회문(回文: madam이나 nurses run처럼 앞에서부터 읽으나 뒤에서부터 읽으나 동일한 단어나 구) 면 true 아니면 False를 반환하는 문제이다.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
queue = collections.deque()
if not head:
return True
node = head
while node is not None :
queue.append(node.val)
node = node.next
while len(queue) > 1:
if queue.pop() != queue.popleft():
return False
return True
어떻게 비교를 할지 고민했는데
pop()과 popleft()를 이용하여 맨 왼쪽과 맨 오른쪽을 비교하는 풀이가 있었다
예시:
from collections import deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
2022.06.02
복습
크게 어려운점은 없었음