My two hash approach


  • 0
    I

    not fast, it takes 3ms, but this approach access each node 1 and only once

    public class Solution {
        int lhash = 0, rhash = 0;
        public boolean isPalindrome(ListNode head) {
            ListNode p = head;
            int x = 1;
            while(p != null) {
                lhash = lhash*31 + p.val;
                
                rhash = rhash + p.val*x;
                x *= 31;
                
                p = p.next;
            }
            
            return lhash == rhash;
        }
    }
    

Log in to reply
 

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