Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up: Could you do it in O(n) time and O(1) space?
这道题让我们判断一个链表是否为回文链表,LeetCode中关于回文串的题共有六道,除了这道,其他的五道为Palindrome Number 验证回文数字,Validate Palindrome 验证回文字符串,Palindrome Partitioning 拆分回文串,Palindrome Partitioning II 拆分回文串之二和Longest Palindromic Substring 最长回文串.链表比字符串难的地方就在于不能通过坐标来直接访问,而只能从头开始遍历到某个位置。那么根据回文串的特点,我们需要比较对应位置的值是否相等,那么我们首先需要找到链表的中点,这个可以用快慢指针来实现,使用方法可以参见之前的两篇Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树和Reorder List 链表重排序,我们使用快慢指针找中点的原理是fast和slow两个指针,每次快指针走两步,慢指针走一步,等快指针走完时,慢指针的位置就是中点。我们还需要用栈,每次慢指针走一步,都把值存入栈中,等到达中点时,链表的前半段都存入栈中了,由于栈的后进先出的性质,就可以和后半段链表按照回文对应的顺序比较了。代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
# 1. Get the midpoint (slow)
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# 2. Push the second half into the stack
stack = [slow.val]
while slow.next:
slow = slow.next
stack.append(slow.val)
# 3. Comparison
while stack:
if stack.pop() != cur.val:
return False
cur = cur.next
return True
这道题的Follow Up让我们用O(1)的空间,那就是说我们不能使用stack了,那么如果代替stack的作用呢,用stack的目的是为了利用其后进先出的特点,好倒着取出前半段的元素。那么现在我们不用stack了,如何倒着取元素呢。我们可以在找到中点后,将后半段的链表翻转一下,这样我们就可以按照回文的顺序比较了,参见代码如下
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = slow = head
# find the mid node
# 一般走两步的都会是两个判断条件
while fast and fast.next:
fast = fast.next.next
slow = slow.next
pre = None
while slow:
nxt = slow.next
slow.next = pre
pre= slow
slow = nxt
# compare the first and second half nodes
while pre: # while node and head:
if pre.val != head.val:
return False
pre = pre.next
head = head.next
return True
二刷:
1。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
slow = head
fast = head.next
stack = [head.val]
while fast and fast.next:
slow = slow.next
fast = fast.next.next
stack.append(slow.val)
# 通过while lopp后,fast是不是none来判断linkedlist个数是奇数还是偶数,如果是奇数,mid停留在正中间,stack=[1,2,3]后半部分为2,1,需要先pop出3,再进行比较
if not fast:
stack.pop()
while slow.next:
slow = slow.next
node = stack.pop()
if slow.val != node:
return False
return True
2。
注意fast和slow的初始条件都是head, 并且while终止条件是fast and fast.next。这样循环结束时slow停留在中间靠后的位置(偶数个node)。便于我们再反转的时候起始值准确的对应后半部分
Last updated
Was this helpful?