8 line java code, get "Time Limit Exceeded"


  • 0
    T

    8 line java code, get "Time Limit Exceeded", i assume it caused by the max length of String(which should be 2^32), it would be good to get some other eyes on it and give some suggestion. i also tried StringBuffer/Builder, but get the same result.

        public boolean isPalindrome(ListNode head) {
            if (head == null || head.next == null) return true;
            String a = "" + head.val;
            String b = "" + head.val;
            while (head.next != null) {
                a = a + head.next.val;
                b = head.next.val + b;
                head = head.next;
            }
            return a.equals(b) ? true : false;     
        }
    

Log in to reply
 

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