Why does my code give time limit exceeded?


  • 0
    U
        public boolean isPalindrome(ListNode head) {
        if(null == head || null == head.next) return true;
         StringBuilder first = new StringBuilder();
        StringBuilder second = new StringBuilder();
        
        ListNode node1 = head;
        ListNode node2 = head;
        while(null != node2 && null != node2.next) {
            first.append(node1.val);
            node1 = node1.next;
            node2 = node2.next.next;
        }
        if(node2 != null)
            node1 = node1.next;
        while(node1 != null) {
            second.insert(0,node1.val);
            node1 = node1.next;
        }   
        return first.toString().equals(second.toString());
    }
    

    I think it only takes O(n). pls help me.


  • 0
    A

    Maybe it is because the append and insert method consume too much time which result in the TLE.


Log in to reply
 

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