Java AC solution using HashMap with O(n) time and O(1) space


  • 0
    G
    class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head == null)
                return true;
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            int i = 0, j = 0;
            ListNode node = head;
            
            while(true)
            {
                map.put(j, node.val);
                node = node.next;
                
                if(node != null)
                    j++;
                else
                    break;
            }
            
            while(i <= j)
            {
                if(map.get(i).intValue() != map.get(j).intValue())
                    return false;
                i++;
                j--;
            }
            return true;
        }
    }
    

Log in to reply
 

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