엔지니어 게시판
LeetCode 솔루션 분류

[8/23] 234. Palindrome Linked List

컨텐츠 정보

본문

Easy
10588624Add to ListShare

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

 

Follow up: Could you do it in O(n) time and O(1) space?
Accepted
1,113,887
Submissions
2,317,041

관련자료

댓글 2

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 1549 ms, faster than 15.03% of Python3 online submissions for Palindrome Linked List.
Memory Usage: 39.2 MB, less than 65.33% of Python3 online submissions for Palindrome Linked List.
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        if not head or not head.next: return True
        
        slow = fast = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        prev = None
        while slow:
            nxt = slow.next
            slow.next = prev
            prev = slow
            slow = nxt
        
        first, second = head, prev 
        
        while second:
            if second.val != first.val: return False
            first, second = first.next, second.next
        
        return True
#         1 2 3 2 1
#         s
#         f
#           s f
#             s.  f
            
#         1 2 2 1
#         s
#         f
#           s f
#             s.   f

재민재민님의 댓글

  • 익명
  • 작성일
Runtime: 294 ms, faster than 75.01% of C++ online submissions for Palindrome Linked List.
Memory Usage: 128.3 MB, less than 14.42% of C++ online submissions for Palindrome Linked List.

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> v;
        while(head) {
            v.push_back(head->val);
            head = head->next;
        }
        
        for(int i = 0; i < v.size()/2; i++)
            if(v[i] != v[v.size()-1-i])
                return false;
        return true;
        
    }
};
전체 410 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 573 명
  • 오늘 방문자 7,254 명
  • 어제 방문자 9,517 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,599 명
알림 0