234.回文链表 (Python3)

Problem: 234. 回文链表

思路

参考:

  • https://leetcode.cn/problems/palindrome-linked-list/solutions/457059/hui-wen-lian-biao-by-leetcode-solution

解题方法

  1. 结合官方题解,列表一般有两种实现,即数组或链表,此处代码中的预定义以明确是采用链表实现。由于链表本身为读取带来一定困难,所以我们常常将链表内容复制入数组,再进行后续考虑;
  2. 熟悉 python中的数组实现,即列表list数据结构,其读取时间复杂度为 O ( 1 ) O(1) O(1)
  3. 学会从预定义内容中看明白链表的操作,对链表有所了解,明白节点的值与指针的概念,并学会如何访问节点的值与更新指针;
  4. 通过循环实现对链表内容到数组的复制;
  5. 结合python的特性,构建反转列表非常简单,即nums[::-1],可以快速进行原数组与反转数组的比较,若两者相同,便是回文!

以下内容为 GPT 对 nums[::-1] 解释:

In Python, nums[::-1] is a common way to create a reversed copy of a list. This slice notation is a powerful feature in Python for list manipulation. Let’s break it down:

  • nums is your list.

  • The : inside the square brackets is the slicing operator, and it’s used to select a portion of the list.

  • The -1 after the second colon specifies the step. In this context, it means we’re moving backward through the list, one element at a time.

So, nums[::-1] starts from the end of the list and steps backward until it reaches the beginning, effectively creating a reversed copy of the list.

In the context of your code, return nums == nums[::-1] is checking whether the list nums is equal to its reversed version. This is a way to check if the list is a palindrome:

  • If nums is the same as nums[::-1], it means the list reads the same forwards and backwards, and the function will return True, indicating the list is a palindrome.

  • If nums is different from nums[::-1], the function will return False, indicating the list is not a palindrome.

复杂度

时间复杂度:

O ( n ) O(n) O(n)

空间复杂度:

O ( n ) O(n) O(n)

Code

# 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:

        # 先把链表内容复制进入数组中
        nums = [] # 创建一个空数组/列表,用来先讲链表复制到数组中
        curr = head # 创建 curr 指向 head
        while curr is not None: # 如果指针不为空
            nums.append(curr.val) # 将当前指针所指的 value 复制添加进入数组
            curr = curr.next # 更新 curr 指针

        # 直接比较原数组/列表和反转数组/列表
        return nums == nums[::-1]
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值