【发布时间】:2016-06-13 14:35:36
【问题描述】:
这是 #234 Leetcode 问题:
给定一个单链表,判断它是否是回文。
跟进:你能在 O(n) 时间和 O(1) 空间内完成吗?
这个问题很容易用 O(n) 空间解决。但是,我无法弄清楚 O(1) 解决方案。我想到的唯一方法是使用递归:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
current = None
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
self.current = head
return self.compare(head)
def compare(self, head):
if not head: return True
if not self.compare(head.next): return False
if head.val != self.current.val:
return False
else:
self.current = self.current.next
return True
这适用于小样本,但给出了
超出最大递归深度
任何人都可以提供仅使用 O(1) 空间的解决方案吗?谢谢。
【问题讨论】:
-
递归也使用 O(n) 空间。它只是更加隐藏,因为这个空间是在堆栈上隐式分配的。
-
如果你的递归使用了常量空间,你就不会耗尽空间。
-
@SvenMarnach 你能解释的更详细一点吗?是什么导致了隐式分配?
-
@molbdnilo 我找不到问题
-
@GilbertLee 您的参数占用空间。该空间与列表的长度呈线性关系。
标签: python algorithm linked-list palindrome