LeetCode 234. Palindrome Linked List 回文链表 Python

Python 234. Palindrome Linked List 回文链接列表

源代码

难度: Easy

题目:

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false
Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

思路:

这道题让我们判断一个singly linked list是否回文,如果不使用额外空间,直接判断的话会比较难想。换一种角度,如果这个不是链表而是数组呢?在Python中,判断数组是否回文可以用一个非常awesome的方法:slice notation

也就是反向切片

[::-1]

若考虑follow up(不使用额外空间),有更好的思路欢迎轰炸我的评论区

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        arr, cur = [], head
        while cur:  # linked list -> array
            arr.append(cur.val)
            cur = cur.next  # go ahead
        return arr == arr[::-1]
        

测试结果:

Accepted!

Runtime: 68 ms, faster than 73.41% of Python3 online submissions for Palindrome Linked List.

Memory Usage: 22.9 MB, less than 100.00% of Python3 online submissions for Palindrome Linked List.

复杂度分析:

Time Complexity: O(n)

Space Complexity: O(n)

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页