本文正在参与掘金团队号上线活动,点击 查看大厂春招职位
题目链接:LeetCode 234. 回文链表
难度:简单 (个人觉得不简单...)
一、题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
二、思路分析
为了方便说用3->1->2->2->1->3->NULL为例,对于第一个节点3,如果有一个函数,返回1->2->2->1->...是否为回文链表,同时也返回最后一个结点3,就可以判断当前链表是否为回文子串了。
于是由了这么一个函数realIsPalindrome(head) -> bool, Node:,按照这种做法,1->2->2->1->...会进一步到2->2->...,最里边好像没法做了。
其实可以用一个长度来记录当前函数应该关注的链表长度,这样长度为0\1\2的时候就很好判断,然后其他长度可以递归判断了。最终如代码所示。
三、AC 代码
def isPalindrome(self, head: ListNode) -> bool:
if not head:
return True
def lengthOfList(head):
p = head
cnt = 0
while p:
p = p.next
cnt+=1
return cnt
def realIsPalindrome(head, length):
if length == 1:
return True, head.next
if length == 2:
return head.val == head.next.val, head.next.next
res, peer = realIsPalindrome(head.next,length-2)
if not res or peer is None:
return False, None
return head.val == peer.val, peer.next
length = lengthOfList(head)
res,_ = realIsPalindrome(head, length )
return res
四、总结
说是用O(1)空间复杂度,其实需要不断递归,用的栈长度,其实还是O(n).
如果你觉的还不错的话,给我点个赞吧💐