Beat 99% python code


  • 0
    J
    class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head:
            return True
        fast=slow=head
        while fast and fast.next:
            fast=fast.next.next
            slow=slow.next
        if fast:
            slow=slow.next
        slow=self.reverse(slow)
        while slow and head.val==slow.val:
            head=head.next
            slow=slow.next
        return slow==None
        
    def reverse(self,head):
        reverse=None
        cur=head
        while cur:
            temp=cur.next
            cur.next=reverse
            reverse=cur
            cur=temp
        return reverse

  • 0
    U

    'if not head' saves a lot time. the rest are not faster than normal implementations


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.