Time Limit Exceeded for Palindrome linked list


  • 0
    H

    Hi there, This is my code for "Palindrome Linked List" and I get "Time Limit Exceeded" error. Would you please let me know what's wrong with my code?

    
    public class Solution {
        public boolean isPalindrome(ListNode head) {
         
         if (head==null)
            return true;
        
         int count =0;
         ListNode p =head;
         while (p!=null)
         {
             p = p.next;
             count++;
         }
         if (count==1){
             return true;
         }
         if (count==2){
             if (head.val==head.next.val)
               return true;
             else 
               return false;
         }
         ListNode middle = head;
         int N_count = count/2;
         for (int i=1;i<=N_count;i++){
             middle = middle.next;
         }
         int max_count = N_count;
         if (count%2==0){ //even
            max_count--;
          }
         
         int hop_right = max_count;
         for(int i=1;i<=N_count;i++){
             
             ListNode left = head;
             ListNode right = middle;
             for(int j=1;j<=hop_right;j++){
                 right = right.next;
             }
             int hop_left = max_count-hop_right;
             for(int j=1;j<=hop_left;j++){
                 left = left.next;
             }
             if (left.val!=right.val){
                 return false;
             }
             else
             {
                 hop_right--;
             }
         }
         return true;
         
        }
    }
    

  • 0

    Please read the question first, and then begin to write your code. The question let us use O(n) time to do this. However I think your code doesn't fit.


Log in to reply
 

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