Python
# 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:
res = list()
cur = head
while cur:
res.append(cur.val)
cur = cur.next
i, j = 0, len(res)-1
while i <= j:
if res[i] != res[j]:
return False
i += 1
j -= 1
return True
Java
法1:递归,O(N) + O(N)
class Solution {
ListNode left; // 标记左侧TreeNode
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
left = head;
return judge(head);
}
public boolean judge(ListNode root) {
if (root == null) {
return true;
}
boolean res = judge(root.next);
res = res && (left.val == root.val);
left = left.next;
return res;
}
}
如果把空间复杂度改为O(1),则会非常复杂。
文章讲述了如何使用递归方法判断链表是否是回文,初始版本空间复杂度为O(N),然后讨论了如何将空间复杂度降低到O(1),但指出这会导致算法复杂度增加。
75

被折叠的 条评论
为什么被折叠?



